home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / updates / update18.zoo / libg++ / src / regex.cc < prev    next >
Encoding:
C/C++ Source or Header  |  1992-03-22  |  81.8 KB  |  2,764 lines

  1. /* Extended regular expression matching and search library.
  2.    Copyright (C) 1985, 1989-90 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. // This is a translation into C++ of regex.c, the GNU regexp package.
  20.  
  21. /* To test, compile with -Dtest.  This Dtestable feature turns this into
  22.    a self-contained program which reads a pattern, describes how it
  23.    compiles, then reads a string and searches for it.
  24.    
  25.    On the other hand, if you compile with both -Dtest and -Dcanned you
  26.    can run some tests we've already thought of.  */
  27.  
  28. /* AIX requires the alloca decl to be the first thing in the file. */
  29. #ifdef __GNUC__
  30. #define alloca __builtin_alloca
  31. #else
  32. #ifdef sparc
  33. #include <alloca.h>
  34. #else
  35. #ifdef _AIX
  36. #pragma alloca
  37. #else
  38. char *alloca ();
  39. #endif
  40. #endif
  41. #endif
  42.  
  43. #ifdef emacs
  44.  
  45. /* The `emacs' switch turns on certain special matching commands
  46.   that make sense only in emacs. */
  47.  
  48. #include "config.h"
  49. #include "lisp.h"
  50. #include "buffer.h"
  51. #include "syntax.h"
  52.  
  53. #else  /* not emacs */
  54.  
  55. #include <string.h>
  56.  
  57. #if defined (USG) || defined (STDC_HEADERS)
  58. #if !(defined(BSTRING) || defined(atarist))
  59. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  60. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  61. #define bzero(s,n)    memset((s),0,(n))
  62. #endif
  63. #endif
  64.  
  65. #include <stdlib.h>
  66.  
  67. /* Define the syntax stuff, so we can do the \<, \>, etc.  */
  68.  
  69. /* This must be nonzero for the wordchar and notwordchar pattern
  70.    commands in re_match_2.  */
  71. #ifndef Sword 
  72. #define Sword 1
  73. #endif
  74.  
  75. #define SYNTAX(c) re_syntax_table[c]
  76.  
  77.  
  78. #ifdef SYNTAX_TABLE
  79.  
  80. char *re_syntax_table;
  81.  
  82. #else /* not SYNTAX_TABLE */
  83.  
  84. static char re_syntax_table[256];
  85.  
  86.  
  87. static void
  88. init_syntax_once ()
  89. {
  90.    register int c;
  91.    static int done = 0;
  92.  
  93.    if (done)
  94.      return;
  95.  
  96.    bzero (re_syntax_table, sizeof re_syntax_table);
  97.  
  98.    for (c = 'a'; c <= 'z'; c++)
  99.      re_syntax_table[c] = Sword;
  100.  
  101.    for (c = 'A'; c <= 'Z'; c++)
  102.      re_syntax_table[c] = Sword;
  103.  
  104.    for (c = '0'; c <= '9'; c++)
  105.      re_syntax_table[c] = Sword;
  106.  
  107.    done = 1;
  108. }
  109.  
  110. #endif /* SYNTAX_TABLE */
  111. #endif /* emacs */
  112.  
  113. /* We write fatal error messages on standard error.  */
  114. #include <stdio.h>
  115.  
  116. /* isalpha(3) etc. are used for the character classes.  */
  117. #include <ctype.h>
  118. /* Sequents are missing isgraph.  */
  119. #ifndef isgraph
  120. #define isgraph(c) (isprint((c)) && !isspace((c)))
  121. #endif
  122.  
  123. /* Get the interface, including the syntax bits.  */
  124. #include "regex.h"
  125.  
  126.  
  127. /* These are the command codes that appear in compiled regular
  128.    expressions, one per byte.  Some command codes are followed by
  129.    argument bytes.  A command code can specify any interpretation
  130.    whatsoever for its arguments.  Zero-bytes may appear in the compiled
  131.    regular expression.
  132.    
  133.    The value of `exactn' is needed in search.c (search_buffer) in emacs.
  134.    So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
  135.    `exactn' we use here must also be 1.  */
  136.  
  137. enum regexpcode
  138.   {
  139.     unused=0,
  140.     exactn=1, /* Followed by one byte giving n, then by n literal bytes.  */
  141.     begline,  /* Fail unless at beginning of line.  */
  142.     endline,  /* Fail unless at end of line.  */
  143.     jump,     /* Followed by two bytes giving relative address to jump to.  */
  144.     on_failure_jump,     /* Followed by two bytes giving relative address of 
  145.                 place to resume at in case of failure.  */
  146.     finalize_jump,     /* Throw away latest failure point and then jump to 
  147.                 address.  */
  148.     maybe_finalize_jump, /* Like jump but finalize if safe to do so.
  149.                 This is used to jump back to the beginning
  150.                 of a repeat.  If the command that follows
  151.                 this jump is clearly incompatible with the
  152.                 one at the beginning of the repeat, such that
  153.                 we can be sure that there is no use backtracking
  154.                 out of repetitions already completed,
  155.                 then we finalize.  */
  156.     dummy_failure_jump,  /* Jump, and push a dummy failure point. This 
  157.                 failure point will be thrown away if an attempt 
  158.                             is made to use it for a failure. A + construct 
  159.                             makes this before the first repeat.  Also
  160.                             use it as an intermediary kind of jump when
  161.                             compiling an or construct.  */
  162.     succeed_n,     /* Used like on_failure_jump except has to succeed n times;
  163.             then gets turned into an on_failure_jump. The relative
  164.                     address following it is useless until then.  The
  165.                     address is followed by two bytes containing n.  */
  166.     jump_n,     /* Similar to jump, but jump n times only; also the relative
  167.             address following is in turn followed by yet two more bytes
  168.                     containing n.  */
  169.     set_number_at,    /* Set the following relative location to the
  170.                subsequent number.  */
  171.     anychar,     /* Matches any (more or less) one character.  */
  172.     charset,     /* Matches any one char belonging to specified set.
  173.             First following byte is number of bitmap bytes.
  174.             Then come bytes for a bitmap saying which chars are in.
  175.             Bits in each byte are ordered low-bit-first.
  176.             A character is in the set if its bit is 1.
  177.             A character too large to have a bit in the map
  178.             is automatically not in the set.  */
  179.     charset_not, /* Same parameters as charset, but match any character
  180.                     that is not one of those specified.  */
  181.     start_memory, /* Start remembering the text that is matched, for
  182.             storing in a memory register.  Followed by one
  183.                     byte containing the register number.  Register numbers
  184.                     must be in the range 0 through RE_NREGS.  */
  185.     stop_memory, /* Stop remembering the text that is matched
  186.             and store it in a memory register.  Followed by
  187.                     one byte containing the register number. Register
  188.                     numbers must be in the range 0 through RE_NREGS.  */
  189.     duplicate,   /* Match a duplicate of something remembered.
  190.             Followed by one byte containing the index of the memory 
  191.                     register.  */
  192. #ifdef emacs
  193.     before_dot,     /* Succeeds if before point.  */
  194.     at_dot,     /* Succeeds if at point.  */
  195.     after_dot,     /* Succeeds if after point.  */
  196. #endif
  197.     begbuf,      /* Succeeds if at beginning of buffer.  */
  198.     endbuf,      /* Succeeds if at end of buffer.  */
  199.     wordchar,    /* Matches any word-constituent character.  */
  200.     notwordchar, /* Matches any char that is not a word-constituent.  */
  201.     wordbeg,     /* Succeeds if at word beginning.  */
  202.     wordend,     /* Succeeds if at word end.  */
  203.     wordbound,   /* Succeeds if at a word boundary.  */
  204.     notwordbound,/* Succeeds if not at a word boundary.  */
  205. #ifdef emacs
  206.     syntaxspec,  /* Matches any character whose syntax is specified.
  207.             followed by a byte which contains a syntax code,
  208.                     e.g., Sword.  */
  209.     notsyntaxspec /* Matches any character whose syntax differs from
  210.                      that specified.  */
  211. #endif
  212.   };
  213.  
  214.  
  215. /* Number of failure points to allocate space for initially,
  216.    when matching.  If this number is exceeded, more space is allocated,
  217.    so it is not a hard limit.  */
  218.  
  219. #ifndef NFAILURES
  220. #define NFAILURES 80
  221. #endif
  222.  
  223. #ifdef CHAR_UNSIGNED
  224. #define SIGN_EXTEND_CHAR(c) ((c)>(char)127?(c)-256:(c)) /* for IBM RT */
  225. #endif
  226. #ifndef SIGN_EXTEND_CHAR
  227. #define SIGN_EXTEND_CHAR(x) (x)
  228. #endif
  229.  
  230.  
  231. /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
  232. #define STORE_NUMBER(destination, number)                \
  233.   { (destination)[0] = (number) & 0377;                    \
  234.     (destination)[1] = (number) >> 8; }
  235.   
  236. /* Same as STORE_NUMBER, except increment the destination pointer to
  237.    the byte after where the number is stored.  Watch out that values for
  238.    DESTINATION such as p + 1 won't work, whereas p will.  */
  239. #define STORE_NUMBER_AND_INCR(destination, number)            \
  240.   { STORE_NUMBER(destination, number);                    \
  241.     (destination) += 2; }
  242.  
  243.  
  244. /* Put into DESTINATION a number stored in two contingous bytes starting
  245.    at SOURCE.  */
  246. #define EXTRACT_NUMBER(destination, source)                \
  247.   { (destination) = *(source) & 0377;                    \
  248.     (destination) += SIGN_EXTEND_CHAR (*(char *)((source) + 1)) << 8; }
  249.  
  250. /* Same as EXTRACT_NUMBER, except increment the pointer for source to
  251.    point to second byte of SOURCE.  Note that SOURCE has to be a value
  252.    such as p, not, e.g., p + 1. */
  253. #define EXTRACT_NUMBER_AND_INCR(destination, source)            \
  254.   { EXTRACT_NUMBER (destination, source);                \
  255.     (source) += 2; }
  256.  
  257.  
  258. /* Specify the precise syntax of regexps for compilation.  This provides
  259.    for compatibility for various utilities which historically have
  260.    different, incompatible syntaxes.
  261.    
  262.    The argument SYNTAX is a bit-mask comprised of the various bits
  263.    defined in regex.h.  */
  264.  
  265. int
  266. re_set_syntax (int syntax)
  267. {
  268.   int ret;
  269.  
  270.   ret = obscure_syntax;
  271.   obscure_syntax = syntax;
  272.   return ret;
  273. }
  274.  
  275. /* Set by re_set_syntax to the current regexp syntax to recognize.  */
  276. int obscure_syntax = 0;
  277.  
  278.  
  279.  
  280. /* Macros for re_compile_pattern, which is found below these definitions.  */
  281.  
  282. #define CHAR_CLASS_MAX_LENGTH  6
  283.  
  284. /* Fetch the next character in the uncompiled pattern, translating it if
  285.    necessary.  */
  286. #define PATFETCH(c)                            \
  287.   {if (p == pend) goto end_of_pattern;                    \
  288.   c = * (unsigned char *) p++;                        \
  289.   if (translate) c = translate[c]; }
  290.  
  291. /* Fetch the next character in the uncompiled pattern, with no
  292.    translation.  */
  293. #define PATFETCH_RAW(c)                            \
  294.  {if (p == pend) goto end_of_pattern;                    \
  295.   c = * (unsigned char *) p++; }
  296.  
  297. #define PATUNFETCH p--
  298.  
  299.  
  300. /* If the buffer isn't allocated when it comes in, use this.  */
  301. #define INIT_BUF_SIZE  28
  302.  
  303. /* Make sure we have at least N more bytes of space in buffer.  */
  304. #define GET_BUFFER_SPACE(n)                        \
  305.   {                                        \
  306.     while (b - bufp->buffer + (n) >= bufp->allocated)            \
  307.       EXTEND_BUFFER;                            \
  308.   }
  309.  
  310. /* Make sure we have one more byte of buffer space and then add CH to it.  */
  311. #define BUFPUSH(ch)                            \
  312.   {                                    \
  313.     GET_BUFFER_SPACE (1);                        \
  314.     *b++ = (char) (ch);                            \
  315.   }
  316.   
  317. /* Extend the buffer by twice its current size via reallociation and
  318.    reset the pointers that pointed into the old allocation to point to
  319.    the correct places in the new allocation.  If extending the buffer
  320.    results in it being larger than 1 << 16, then flag memory exhausted.  */
  321. #define EXTEND_BUFFER                            \
  322.   { char *old_buffer = bufp->buffer;                    \
  323.     if (bufp->allocated == (1L<<16)) goto too_big;            \
  324.     bufp->allocated *= 2;                        \
  325.     if (bufp->allocated > (1L<<16)) bufp->allocated = (1L<<16);        \
  326.     bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated);    \
  327.     if (bufp->buffer == 0)                        \
  328.       goto memory_exhausted;                        \
  329.     b = (b - old_buffer) + bufp->buffer;                \
  330.     if (fixup_jump)                            \
  331.       fixup_jump = (fixup_jump - old_buffer) + bufp->buffer;        \
  332.     if (laststart)                            \
  333.       laststart = (laststart - old_buffer) + bufp->buffer;        \
  334.     begalt = (begalt - old_buffer) + bufp->buffer;            \
  335.     if (pending_exact)                            \
  336.       pending_exact = (pending_exact - old_buffer) + bufp->buffer;    \
  337.   }
  338.  
  339. /* Set the bit for character C in a character set list.  */
  340. #define SET_LIST_BIT(c)  (b[(c) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
  341.  
  342. /* Get the next unsigned number in the uncompiled pattern.  */
  343. #define GET_UNSIGNED_NUMBER(num)                     \
  344.   { if (p != pend)                             \
  345.       {                                 \
  346.         PATFETCH (c);                             \
  347.     while (isdigit (c))                         \
  348.       {                                 \
  349.         if (num < 0)                         \
  350.            num = 0;                         \
  351.             num = num * 10 + c - '0';                     \
  352.         if (p == pend)                         \
  353.            break;                             \
  354.         PATFETCH (c);                         \
  355.       }                                 \
  356.         }                                 \
  357.   }
  358.  
  359. /* Subroutines for re_compile_pattern.  */
  360. static void store_jump (char *from, char opcode, char *to);
  361. static void insert_jump (char op, char *from, char *to, char *current_end);
  362. static void store_jump_n  (char *from, char opcode, char *to, unsigned n);
  363. static void insert_jump_n (char, char *, char *, char *, unsigned);
  364. static void insert_op_2 (char, char *, char *_end, int, int);
  365.  
  366.  
  367. /* re_compile_pattern takes a regular-expression string
  368.    and converts it into a buffer full of byte commands for matching.
  369.  
  370.    PATTERN   is the address of the pattern string
  371.    SIZE      is the length of it.
  372.    BUFP        is a  struct re_pattern_buffer *  which points to the info
  373.          on where to store the byte commands.
  374.          This structure contains a  char *  which points to the
  375.          actual space, which should have been obtained with malloc.
  376.          re_compile_pattern may use realloc to grow the buffer space.
  377.  
  378.    The number of bytes of commands can be found out by looking in
  379.    the `struct re_pattern_buffer' that bufp pointed to, after
  380.    re_compile_pattern returns. */
  381.  
  382. char *
  383. re_compile_pattern (char *pattern, int size, struct re_pattern_buffer *bufp)
  384. {
  385.   register char *b = bufp->buffer;
  386.   register char *p = pattern;
  387.   char *pend = pattern + size;
  388.   register unsigned c, c1;
  389.   char *p1;
  390.   unsigned char *translate = (unsigned char *) bufp->translate;
  391.  
  392.   /* Address of the count-byte of the most recently inserted `exactn'
  393.      command.  This makes it possible to tell whether a new exact-match
  394.      character can be added to that command or requires a new `exactn'
  395.      command.  */
  396.      
  397.   char *pending_exact = 0;
  398.  
  399.   /* Address of the place where a forward-jump should go to the end of
  400.      the containing expression.  Each alternative of an `or', except the
  401.      last, ends with a forward-jump of this sort.  */
  402.  
  403.   char *fixup_jump = 0;
  404.  
  405.   /* Address of start of the most recently finished expression.
  406.      This tells postfix * where to find the start of its operand.  */
  407.  
  408.   char *laststart = 0;
  409.  
  410.   /* In processing a repeat, 1 means zero matches is allowed.  */
  411.  
  412.   char zero_times_ok;
  413.  
  414.   /* In processing a repeat, 1 means many matches is allowed.  */
  415.  
  416.   char many_times_ok;
  417.  
  418.   /* Address of beginning of regexp, or inside of last \(.  */
  419.  
  420.   char *begalt = b;
  421.  
  422.   /* In processing an interval, at least this many matches must be made.  */
  423.   int lower_bound;
  424.  
  425.   /* In processing an interval, at most this many matches can be made.  */
  426.   int upper_bound;
  427.  
  428.   /* Place in pattern (i.e., the {) to which to go back if the interval
  429.      is invalid.  */
  430.   char *beg_interval = 0;
  431.   
  432.   /* Stack of information saved by \( and restored by \).
  433.      Four stack elements are pushed by each \(:
  434.        First, the value of b.
  435.        Second, the value of fixup_jump.
  436.        Third, the value of regnum.
  437.        Fourth, the value of begalt.  */
  438.  
  439.   int stackb[40];
  440.   int *stackp = stackb;
  441.   int *stacke = stackb + 40;
  442.   int *stackt;
  443.  
  444.   /* Counts \('s as they are encountered.  Remembered for the matching \),
  445.      where it becomes the register number to put in the stop_memory
  446.      command.  */
  447.  
  448.   unsigned regnum = 1;
  449.  
  450.   bufp->fastmap_accurate = 0;
  451.  
  452. #ifndef emacs
  453. #ifndef SYNTAX_TABLE
  454.   /* Initialize the syntax table.  */
  455.    init_syntax_once();
  456. #endif
  457. #endif
  458.  
  459.   if (bufp->allocated == 0)
  460.     {
  461.       bufp->allocated = INIT_BUF_SIZE;
  462.       if (bufp->buffer)
  463.     /* EXTEND_BUFFER loses when bufp->allocated is 0.  */
  464.     bufp->buffer = (char *) realloc (bufp->buffer, INIT_BUF_SIZE);
  465.       else
  466.     /* Caller did not allocate a buffer.  Do it for them.  */
  467.     bufp->buffer = (char *) malloc (INIT_BUF_SIZE);
  468.       if (!bufp->buffer) goto memory_exhausted;
  469.       begalt = b = bufp->buffer;
  470.     }
  471.  
  472.   while (p != pend)
  473.     {
  474.       PATFETCH (c);
  475.  
  476.       switch (c)
  477.     {
  478.     case '$':
  479.       {
  480.         char *p1 = p;
  481.         /* When testing what follows the $,
  482.            look past the \-constructs that don't consume anything.  */
  483.         if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  484.           while (p1 != pend)
  485.         {
  486.           if (*p1 == '\\' && p1 + 1 != pend
  487.               && (p1[1] == '<' || p1[1] == '>'
  488.               || p1[1] == '`' || p1[1] == '\''
  489. #ifdef emacs
  490.               || p1[1] == '='
  491. #endif
  492.               || p1[1] == 'b' || p1[1] == 'B'))
  493.             p1 += 2;
  494.           else
  495.             break;
  496.         }
  497.             if (obscure_syntax & RE_TIGHT_VBAR)
  498.           {
  499.         if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS) && p1 != pend)
  500.           goto normal_char;
  501.         /* Make operand of last vbar end before this `$'.  */
  502.         if (fixup_jump)
  503.           store_jump (fixup_jump, jump, b);
  504.         fixup_jump = 0;
  505.         BUFPUSH (endline);
  506.         break;
  507.           }
  508.         /* $ means succeed if at end of line, but only in special contexts.
  509.           If validly in the middle of a pattern, it is a normal character. */
  510.  
  511.             if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS) && p1 != pend)
  512.           goto invalid_pattern;
  513.         if (p1 == pend || *p1 == '\n'
  514.         || (obscure_syntax & RE_CONTEXT_INDEP_OPS)
  515.         || (obscure_syntax & RE_NO_BK_PARENS
  516.             ? *p1 == ')'
  517.             : *p1 == '\\' && p1[1] == ')')
  518.         || (obscure_syntax & RE_NO_BK_VBAR
  519.             ? *p1 == '|'
  520.             : *p1 == '\\' && p1[1] == '|'))
  521.           {
  522.         BUFPUSH (endline);
  523.         break;
  524.           }
  525.         goto normal_char;
  526.           }
  527.     case '^':
  528.       /* ^ means succeed if at beg of line, but only if no preceding 
  529.              pattern.  */
  530.              
  531.           if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS) && laststart)
  532.             goto invalid_pattern;
  533.           if (laststart && p - 2 >= pattern && p[-2] != '\n'
  534.            && !(obscure_syntax & RE_CONTEXT_INDEP_OPS))
  535.         goto normal_char;
  536.       if (obscure_syntax & RE_TIGHT_VBAR)
  537.         {
  538.           if (p != pattern + 1
  539.           && ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  540.         goto normal_char;
  541.           BUFPUSH (begline);
  542.           begalt = b;
  543.         }
  544.       else
  545.         BUFPUSH (begline);
  546.       break;
  547.  
  548.     case '+':
  549.     case '?':
  550.       if ((obscure_syntax & RE_BK_PLUS_QM)
  551.           || (obscure_syntax & RE_LIMITED_OPS))
  552.         goto normal_char;
  553.     handle_plus:
  554.     case '*':
  555.       /* If there is no previous pattern, char not special. */
  556.       if (!laststart)
  557.             {
  558.               if (obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
  559.                 goto invalid_pattern;
  560.               else if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
  561.         goto normal_char;
  562.             }
  563.       /* If there is a sequence of repetition chars,
  564.          collapse it down to just one.  */
  565.       zero_times_ok = 0;
  566.       many_times_ok = 0;
  567.       while (1)
  568.         {
  569.           zero_times_ok |= c != '+';
  570.           many_times_ok |= c != '?';
  571.           if (p == pend)
  572.         break;
  573.           PATFETCH (c);
  574.           if (c == '*')
  575.         ;
  576.           else if (!(obscure_syntax & RE_BK_PLUS_QM)
  577.                && (c == '+' || c == '?'))
  578.         ;
  579.           else if ((obscure_syntax & RE_BK_PLUS_QM)
  580.                && c == '\\')
  581.         {
  582.           int c1;
  583.           PATFETCH (c1);
  584.           if (!(c1 == '+' || c1 == '?'))
  585.             {
  586.               PATUNFETCH;
  587.               PATUNFETCH;
  588.               break;
  589.             }
  590.           c = c1;
  591.         }
  592.           else
  593.         {
  594.           PATUNFETCH;
  595.           break;
  596.         }
  597.         }
  598.  
  599.       /* Star, etc. applied to an empty pattern is equivalent
  600.          to an empty pattern.  */
  601.       if (!laststart)  
  602.         break;
  603.  
  604.       /* Now we know whether or not zero matches is allowed
  605.          and also whether or not two or more matches is allowed.  */
  606.       if (many_times_ok)
  607.         {
  608.           /* If more than one repetition is allowed, put in at the
  609.                  end a backward relative jump from b to before the next
  610.                  jump we're going to put in below (which jumps from
  611.                  laststart to after this jump).  */
  612.               GET_BUFFER_SPACE (3);
  613.           store_jump (b, maybe_finalize_jump, laststart - 3);
  614.           b += 3;      /* Because store_jump put stuff here.  */
  615.         }
  616.           /* On failure, jump from laststart to b + 3, which will be the
  617.              end of the buffer after this jump is inserted.  */
  618.           GET_BUFFER_SPACE (3);
  619.       insert_jump (on_failure_jump, laststart, b + 3, b);
  620.       pending_exact = 0;
  621.       b += 3;
  622.       if (!zero_times_ok)
  623.         {
  624.           /* At least one repetition is required, so insert a
  625.                  dummy-failure before the initial on-failure-jump
  626.                  instruction of the loop. This effects a skip over that
  627.                  instruction the first time we hit that loop.  */
  628.               GET_BUFFER_SPACE (6);
  629.               insert_jump (dummy_failure_jump, laststart, laststart + 6, b);
  630.           b += 3;
  631.         }
  632.       break;
  633.  
  634.     case '.':
  635.       laststart = b;
  636.       BUFPUSH (anychar);
  637.       break;
  638.  
  639.         case '[':
  640.           if (p == pend)
  641.             goto invalid_pattern;
  642.       while (b - bufp->buffer
  643.          > bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH)
  644.         EXTEND_BUFFER;
  645.  
  646.       laststart = b;
  647.       if (*p == '^')
  648.         {
  649.               BUFPUSH (charset_not); 
  650.               p++;
  651.             }
  652.       else
  653.         BUFPUSH (charset);
  654.       p1 = p;
  655.  
  656.       BUFPUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  657.       /* Clear the whole map */
  658.       bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  659.           
  660.       if ((obscure_syntax & RE_HAT_NOT_NEWLINE) && b[-2] == charset_not)
  661.             SET_LIST_BIT ('\n');
  662.  
  663.  
  664.       /* Read in characters and ranges, setting map bits.  */
  665.       while (1)
  666.         {
  667.           /* Don't translate while fetching, in case it's a range bound.
  668.          When we set the bit for the character, we translate it.  */
  669.           PATFETCH_RAW (c);
  670.  
  671.           /* If set, \ escapes characters when inside [...].  */
  672.           if ((obscure_syntax & RE_AWK_CLASS_HACK) && c == '\\')
  673.             {
  674.               PATFETCH(c1);
  675.                   SET_LIST_BIT (c1);
  676.               continue;
  677.             }
  678.               if (c == ']')
  679.                 {
  680.                   if (p == p1 + 1)
  681.                     {
  682.               /* If this is an empty bracket expression.  */
  683.                       if ((obscure_syntax & RE_NO_EMPTY_BRACKETS) 
  684.                           && p == pend)
  685.                         goto invalid_pattern;
  686.                     }
  687.                   else 
  688.             /* Stop if this isn't merely a ] inside a bracket
  689.                        expression, but rather the end of a bracket
  690.                        expression.  */
  691.                     break;
  692.                 }
  693.               /* Get a range.  */
  694.               if (p[0] == '-' && p[1] != ']')
  695.         {
  696.                   PATFETCH (c1);
  697.           /* Don't translate the range bounds while fetching them.  */
  698.           PATFETCH_RAW (c1);
  699.                   
  700.           if ((obscure_syntax & RE_NO_EMPTY_RANGES) && c > c1)
  701.                     goto invalid_pattern;
  702.                     
  703.           if ((obscure_syntax & RE_NO_HYPHEN_RANGE_END) 
  704.                       && c1 == '-' && *p != ']')
  705.                     goto invalid_pattern;
  706.                     
  707.                   while (c <= c1)
  708.             {
  709.               /* Translate each char that's in the range.  */
  710.               if (translate)
  711.             SET_LIST_BIT (translate[c]);
  712.               else
  713.             SET_LIST_BIT (c);
  714.                       c++;
  715.             }
  716.                 }
  717.           else if ((obscure_syntax & RE_CHAR_CLASSES)
  718.             &&  c == '[' && p[0] == ':')
  719.                 {
  720.           /* Longest valid character class word has six characters.  */
  721.                   char str[CHAR_CLASS_MAX_LENGTH];
  722.           PATFETCH (c);
  723.           c1 = 0;
  724.           /* If no ] at end.  */
  725.                   if (p == pend)
  726.                     goto invalid_pattern;
  727.           while (1)
  728.             {
  729.               /* Don't translate the ``character class'' characters.  */
  730.                       PATFETCH_RAW (c);
  731.               if (c == ':' || c == ']' || p == pend
  732.                           || c1 == CHAR_CLASS_MAX_LENGTH)
  733.                 break;
  734.               str[c1++] = c;
  735.             }
  736.           str[c1] = '\0';
  737.           if (p == pend     
  738.               || c == ']'    /* End of the bracket expression.  */
  739.                       || p[0] != ']'
  740.               || p + 1 == pend
  741.                       || (strcmp (str, "alpha") != 0 
  742.                           && strcmp (str, "upper") != 0
  743.               && strcmp (str, "lower") != 0 
  744.                           && strcmp (str, "digit") != 0
  745.               && strcmp (str, "alnum") != 0 
  746.                           && strcmp (str, "xdigit") != 0
  747.               && strcmp (str, "space") != 0 
  748.                           && strcmp (str, "print") != 0
  749.               && strcmp (str, "punct") != 0 
  750.                           && strcmp (str, "graph") != 0
  751.               && strcmp (str, "cntrl") != 0))
  752.             {
  753.                /* Undo the ending character, the letters, and leave 
  754.                           the leading : and [ (but set bits for them).  */
  755.                       c1++;
  756.               while (c1--)    
  757.             PATUNFETCH;
  758.               SET_LIST_BIT ('[');
  759.               SET_LIST_BIT (':');
  760.                 }
  761.                   else
  762.                     {
  763.                       /* The ] at the end of the character class.  */
  764.                       PATFETCH (c);                    
  765.                       if (c != ']')
  766.                         goto invalid_pattern;
  767.               for (c = 0; c < (1 << BYTEWIDTH); c++)
  768.             {
  769.               if ((strcmp (str, "alpha") == 0  && isalpha (c))
  770.                    || (strcmp (str, "upper") == 0  && isupper (c))
  771.                    || (strcmp (str, "lower") == 0  && islower (c))
  772.                    || (strcmp (str, "digit") == 0  && isdigit (c))
  773.                    || (strcmp (str, "alnum") == 0  && isalnum (c))
  774.                    || (strcmp (str, "xdigit") == 0  && isxdigit (c))
  775.                    || (strcmp (str, "space") == 0  && isspace (c))
  776.                    || (strcmp (str, "print") == 0  && isprint (c))
  777.                    || (strcmp (str, "punct") == 0  && ispunct (c))
  778.                    || (strcmp (str, "graph") == 0  && isgraph (c))
  779.                    || (strcmp (str, "cntrl") == 0  && iscntrl (c)))
  780.                 SET_LIST_BIT (c);
  781.             }
  782.             }
  783.                 }
  784.               else if (translate)
  785.         SET_LIST_BIT (translate[c]);
  786.           else
  787.                 SET_LIST_BIT (c);
  788.         }
  789.  
  790.           /* Discard any character set/class bitmap bytes that are all
  791.              0 at the end of the map. Decrement the map-length byte too.  */
  792.           while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
  793.             b[-1]--; 
  794.           b += b[-1];
  795.           break;
  796.  
  797.     case '(':
  798.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  799.         goto normal_char;
  800.       else
  801.         goto handle_open;
  802.  
  803.     case ')':
  804.       if (! (obscure_syntax & RE_NO_BK_PARENS))
  805.         goto normal_char;
  806.       else
  807.         goto handle_close;
  808.  
  809.         case '\n':
  810.       if (! (obscure_syntax & RE_NEWLINE_OR))
  811.         goto normal_char;
  812.       else
  813.         goto handle_bar;
  814.  
  815.     case '|':
  816.       if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
  817.               && (! laststart  ||  p == pend))
  818.         goto invalid_pattern;
  819.           else if (! (obscure_syntax & RE_NO_BK_VBAR))
  820.         goto normal_char;
  821.       else
  822.         goto handle_bar;
  823.  
  824.     case '{':
  825.            if (! ((obscure_syntax & RE_NO_BK_CURLY_BRACES)
  826.                   && (obscure_syntax & RE_INTERVALS)))
  827.              goto normal_char;
  828.            else
  829.              goto handle_interval;
  830.              
  831.         case '\\':
  832.       if (p == pend) goto invalid_pattern;
  833.       PATFETCH_RAW (c);
  834.       switch (c)
  835.         {
  836.         case '(':
  837.           if (obscure_syntax & RE_NO_BK_PARENS)
  838.         goto normal_backsl;
  839.         handle_open:
  840.           if (stackp == stacke) goto nesting_too_deep;
  841.  
  842.               /* Laststart should point to the start_memory that we are about
  843.                  to push (unless the pattern has RE_NREGS or more ('s).  */
  844.               *stackp++ = b - bufp->buffer;    
  845.           if (regnum < RE_NREGS)
  846.             {
  847.           BUFPUSH (start_memory);
  848.           BUFPUSH (regnum);
  849.             }
  850.           *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
  851.           *stackp++ = regnum++;
  852.           *stackp++ = begalt - bufp->buffer;
  853.           fixup_jump = 0;
  854.           laststart = 0;
  855.           begalt = b;
  856.           break;
  857.  
  858.         case ')':
  859.           if (obscure_syntax & RE_NO_BK_PARENS)
  860.         goto normal_backsl;
  861.         handle_close:
  862.           if (stackp == stackb) goto unmatched_close;
  863.           begalt = *--stackp + bufp->buffer;
  864.           if (fixup_jump)
  865.         store_jump (fixup_jump, jump, b);
  866.           if (stackp[-1] < RE_NREGS)
  867.         {
  868.           BUFPUSH (stop_memory);
  869.           BUFPUSH (stackp[-1]);
  870.         }
  871.           stackp -= 2;
  872.               fixup_jump = *stackp ? *stackp + bufp->buffer - 1 : 0;
  873.               laststart = *--stackp + bufp->buffer;
  874.           break;
  875.  
  876.         case '|':
  877.               if ((obscure_syntax & RE_LIMITED_OPS)
  878.               || (obscure_syntax & RE_NO_BK_VBAR))
  879.         goto normal_backsl;
  880.         handle_bar:
  881.               if (obscure_syntax & RE_LIMITED_OPS)
  882.                 goto normal_char;
  883.           /* Insert before the previous alternative a jump which
  884.                  jumps to this alternative if the former fails.  */
  885.               GET_BUFFER_SPACE (6);
  886.               insert_jump (on_failure_jump, begalt, b + 6, b);
  887.           pending_exact = 0;
  888.           b += 3;
  889.           /* The alternative before the previous alternative has a
  890.                  jump after it which gets executed if it gets matched.
  891.                  Adjust that jump so it will jump to the previous
  892.                  alternative's analogous jump (put in below, which in
  893.                  turn will jump to the next (if any) alternative's such
  894.                  jump, etc.).  The last such jump jumps to the correct
  895.                  final destination.  */
  896.               if (fixup_jump)
  897.         store_jump (fixup_jump, jump, b);
  898.                 
  899.           /* Leave space for a jump after previous alternative---to be 
  900.                  filled in later.  */
  901.               fixup_jump = b;
  902.               b += 3;
  903.  
  904.               laststart = 0;
  905.           begalt = b;
  906.           break;
  907.  
  908.             case '{': 
  909.               if (! (obscure_syntax & RE_INTERVALS)
  910.           /* Let \{ be a literal.  */
  911.                   || ((obscure_syntax & RE_INTERVALS)
  912.                       && (obscure_syntax & RE_NO_BK_CURLY_BRACES))
  913.           /* If it's the string "\{".  */
  914.           || (p - 2 == pattern  &&  p == pend))
  915.                 goto normal_backsl;
  916.             handle_interval:
  917.           beg_interval = p - 1;        /* The {.  */
  918.               /* If there is no previous pattern, this isn't an interval.  */
  919.           if (!laststart)
  920.             {
  921.                   if (obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
  922.             goto invalid_pattern;
  923.                   else
  924.                     goto normal_backsl;
  925.                 }
  926.               /* It also isn't an interval if not preceded by an re
  927.                  matching a single character or subexpression, or if
  928.                  the current type of intervals can't handle back
  929.                  references and the previous thing is a back reference.  */
  930.               if (! (*laststart == anychar
  931.              || *laststart == charset
  932.              || *laststart == charset_not
  933.              || *laststart == start_memory
  934.              || (*laststart == exactn  &&  laststart[1] == 1)
  935.              || (! (obscure_syntax & RE_NO_BK_REFS)
  936.                          && *laststart == duplicate)))
  937.                 {
  938.                   if (obscure_syntax & RE_NO_BK_CURLY_BRACES)
  939.                     goto normal_char;
  940.                     
  941.           /* Posix extended syntax is handled in previous
  942.                      statement; this is for Posix basic syntax.  */
  943.                   if (obscure_syntax & RE_INTERVALS)
  944.                     goto invalid_pattern;
  945.                     
  946.                   goto normal_backsl;
  947.         }
  948.               lower_bound = -1;            /* So can see if are set.  */
  949.           upper_bound = -1;
  950.               GET_UNSIGNED_NUMBER (lower_bound);
  951.           if (c == ',')
  952.         {
  953.           GET_UNSIGNED_NUMBER (upper_bound);
  954.           if (upper_bound < 0)
  955.             upper_bound = RE_DUP_MAX;
  956.         }
  957.           if (upper_bound < 0)
  958.         upper_bound = lower_bound;
  959.               if (! (obscure_syntax & RE_NO_BK_CURLY_BRACES)) 
  960.                 {
  961.                   if (c != '\\')
  962.                     goto invalid_pattern;
  963.                   PATFETCH (c);
  964.                 }
  965.           if (c != '}' || lower_bound < 0 || upper_bound > RE_DUP_MAX
  966.           || lower_bound > upper_bound 
  967.                   || ((obscure_syntax & RE_NO_BK_CURLY_BRACES) 
  968.               && p != pend  && *p == '{')) 
  969.             {
  970.           if (obscure_syntax & RE_NO_BK_CURLY_BRACES)
  971.                     goto unfetch_interval;
  972.                   else
  973.                     goto invalid_pattern;
  974.         }
  975.  
  976.           /* If upper_bound is zero, don't want to succeed at all; 
  977.           jump from laststart to b + 3, which will be the end of
  978.                  the buffer after this jump is inserted.  */
  979.                  
  980.                if (upper_bound == 0)
  981.                  {
  982.                    GET_BUFFER_SPACE (3);
  983.                    insert_jump (jump, laststart, b + 3, b);
  984.                    b += 3;
  985.                  }
  986.  
  987.                /* Otherwise, after lower_bound number of succeeds, jump
  988.                   to after the jump_n which will be inserted at the end
  989.                   of the buffer, and insert that jump_n.  */
  990.                else 
  991.          { /* Set to 5 if only one repetition is allowed and
  992.                   hence no jump_n is inserted at the current end of
  993.                       the buffer; then only space for the succeed_n is
  994.                       needed.  Otherwise, need space for both the
  995.                       succeed_n and the jump_n.  */
  996.                       
  997.                    unsigned slots_needed = upper_bound == 1 ? 5 : 10;
  998.                      
  999.                    GET_BUFFER_SPACE ((int) slots_needed);
  1000.                    /* Initialize the succeed_n to n, even though it will
  1001.                       be set by its attendant set_number_at, because
  1002.                       re_compile_fastmap will need to know it.  Jump to
  1003.                       what the end of buffer will be after inserting
  1004.                       this succeed_n and possibly appending a jump_n.  */
  1005.                    insert_jump_n (succeed_n, laststart, b + slots_needed, 
  1006.                           b, lower_bound);
  1007.                    b += 5;     /* Just increment for the succeed_n here.  */
  1008.  
  1009.           /* More than one repetition is allowed, so put in at
  1010.              the end of the buffer a backward jump from b to the
  1011.                      succeed_n we put in above.  By the time we've gotten
  1012.                      to this jump when matching, we'll have matched once
  1013.                      already, so jump back only upper_bound - 1 times.  */
  1014.  
  1015.                    if (upper_bound > 1)
  1016.                      {
  1017.                        store_jump_n (b, jump_n, laststart, upper_bound - 1);
  1018.                        b += 5;
  1019.                        /* When hit this when matching, reset the
  1020.                           preceding jump_n's n to upper_bound - 1.  */
  1021.                        BUFPUSH (set_number_at);
  1022.                GET_BUFFER_SPACE (2);
  1023.                        STORE_NUMBER_AND_INCR (b, -5);
  1024.                        STORE_NUMBER_AND_INCR (b, upper_bound - 1);
  1025.                      }
  1026.            /* When hit this when matching, set the succeed_n's n.  */
  1027.                    GET_BUFFER_SPACE (5);
  1028.            insert_op_2 (set_number_at, laststart, b, 5, lower_bound);
  1029.                    b += 5;
  1030.                  }
  1031.               pending_exact = 0;
  1032.           beg_interval = 0;
  1033.               break;
  1034.  
  1035.  
  1036.             unfetch_interval:
  1037.           /* If an invalid interval, match the characters as literals.  */
  1038.            if (beg_interval)
  1039.                  p = beg_interval;
  1040.              else
  1041.                  {
  1042.                    fprintf (stderr, 
  1043.               "regex: no interval beginning to which to backtrack.\n");
  1044.            exit (1);
  1045.                  }
  1046.                  
  1047.                beg_interval = 0;
  1048.                PATFETCH (c);        /* normal_char expects char in `c'.  */
  1049.            goto normal_char;
  1050.            break;
  1051.  
  1052. #ifdef emacs
  1053.         case '=':
  1054.           BUFPUSH (at_dot);
  1055.           break;
  1056.  
  1057.         case 's':    
  1058.           laststart = b;
  1059.           BUFPUSH (syntaxspec);
  1060.           PATFETCH (c);
  1061.           BUFPUSH (syntax_spec_code[c]);
  1062.           break;
  1063.  
  1064.         case 'S':
  1065.           laststart = b;
  1066.           BUFPUSH (notsyntaxspec);
  1067.           PATFETCH (c);
  1068.           BUFPUSH (syntax_spec_code[c]);
  1069.           break;
  1070. #endif /* emacs */
  1071.  
  1072.         case 'w':
  1073.           laststart = b;
  1074.           BUFPUSH (wordchar);
  1075.           break;
  1076.  
  1077.         case 'W':
  1078.           laststart = b;
  1079.           BUFPUSH (notwordchar);
  1080.           break;
  1081.  
  1082.         case '<':
  1083.           BUFPUSH (wordbeg);
  1084.           break;
  1085.  
  1086.         case '>':
  1087.           BUFPUSH (wordend);
  1088.           break;
  1089.  
  1090.         case 'b':
  1091.           BUFPUSH (wordbound);
  1092.           break;
  1093.  
  1094.         case 'B':
  1095.           BUFPUSH (notwordbound);
  1096.           break;
  1097.  
  1098.         case '`':
  1099.           BUFPUSH (begbuf);
  1100.           break;
  1101.  
  1102.         case '\'':
  1103.           BUFPUSH (endbuf);
  1104.           break;
  1105.  
  1106.         case '1':
  1107.         case '2':
  1108.         case '3':
  1109.         case '4':
  1110.         case '5':
  1111.         case '6':
  1112.         case '7':
  1113.         case '8':
  1114.         case '9':
  1115.           if (obscure_syntax & RE_NO_BK_REFS)
  1116.                 goto normal_char;
  1117.               c1 = c - '0';
  1118.           if (c1 >= regnum)
  1119.         {
  1120.             if (obscure_syntax & RE_NO_EMPTY_BK_REF)
  1121.                     goto invalid_pattern;
  1122.                   else
  1123.                     goto normal_char;
  1124.                 }
  1125.               /* Can't back reference to a subexpression if inside of it.  */
  1126.               for (stackt = stackp - 2;  stackt > stackb;  stackt -= 4)
  1127.          if (*stackt == c1)
  1128.           goto normal_char;
  1129.           laststart = b;
  1130.           BUFPUSH (duplicate);
  1131.           BUFPUSH (c1);
  1132.           break;
  1133.  
  1134.         case '+':
  1135.         case '?':
  1136.           if (obscure_syntax & RE_BK_PLUS_QM)
  1137.         goto handle_plus;
  1138.           else
  1139.                 goto normal_backsl;
  1140.               break;
  1141.  
  1142.             default:
  1143.         normal_backsl:
  1144.           /* You might think it would be useful for \ to mean
  1145.          not to translate; but if we don't translate it
  1146.          it will never match anything.  */
  1147.           if (translate) c = translate[c];
  1148.           goto normal_char;
  1149.         }
  1150.       break;
  1151.  
  1152.     default:
  1153.     normal_char:        /* Expects the character in `c'.  */
  1154.       if (!pending_exact || pending_exact + *pending_exact + 1 != b
  1155.           || *pending_exact == 0177 || *p == '*' || *p == '^'
  1156.           || ((obscure_syntax & RE_BK_PLUS_QM)
  1157.           ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  1158.           : (*p == '+' || *p == '?'))
  1159.           || ((obscure_syntax & RE_INTERVALS) 
  1160.                   && ((obscure_syntax & RE_NO_BK_CURLY_BRACES)
  1161.               ? *p == '{'
  1162.                       : (p[0] == '\\' && p[1] == '{'))))
  1163.         {
  1164.           laststart = b;
  1165.           BUFPUSH (exactn);
  1166.           pending_exact = b;
  1167.           BUFPUSH (0);
  1168.         }
  1169.       BUFPUSH (c);
  1170.       (*pending_exact)++;
  1171.     }
  1172.     }
  1173.  
  1174.   if (fixup_jump)
  1175.     store_jump (fixup_jump, jump, b);
  1176.  
  1177.   if (stackp != stackb) goto unmatched_open;
  1178.  
  1179.   bufp->used = b - bufp->buffer;
  1180.   return 0;
  1181.  
  1182.  invalid_pattern:
  1183.   return "Invalid regular expression";
  1184.  
  1185.  unmatched_open:
  1186.   return "Unmatched \\(";
  1187.  
  1188.  unmatched_close:
  1189.   return "Unmatched \\)";
  1190.  
  1191.  end_of_pattern:
  1192.   return "Premature end of regular expression";
  1193.  
  1194.  nesting_too_deep:
  1195.   return "Nesting too deep";
  1196.  
  1197.  too_big:
  1198.   return "Regular expression too big";
  1199.  
  1200.  memory_exhausted:
  1201.   return "Memory exhausted";
  1202. }
  1203.  
  1204.  
  1205. /* Store a jump of the form <OPCODE> <relative address>.
  1206.    Store in the location FROM a jump operation to jump to relative
  1207.    address FROM - TO.  OPCODE is the opcode to store.  */
  1208.  
  1209. static void
  1210. store_jump (char *from, char opcode, char *to)
  1211. {
  1212.   from[0] = opcode;
  1213.   STORE_NUMBER(from + 1, to - (from + 3));
  1214. }
  1215.  
  1216.  
  1217. /* Open up space before char FROM, and insert there a jump to TO.
  1218.    CURRENT_END gives the end of the storage not in use, so we know 
  1219.    how much data to copy up. OP is the opcode of the jump to insert.
  1220.  
  1221.    If you call this function, you must zero out pending_exact.  */
  1222.  
  1223. static void
  1224. insert_jump (char op, char *from, char *to, char *current_end)
  1225. {
  1226.   register char *pfrom = current_end;        /* Copy from here...  */
  1227.   register char *pto = current_end + 3;        /* ...to here.  */
  1228.  
  1229.   while (pfrom != from)                   
  1230.     *--pto = *--pfrom;
  1231.   store_jump (from, op, to);
  1232. }
  1233.  
  1234.  
  1235. /* Store a jump of the form <opcode> <relative address> <n> .
  1236.  
  1237.    Store in the location FROM a jump operation to jump to relative
  1238.    address FROM - TO.  OPCODE is the opcode to store, N is a number the
  1239.    jump uses, say, to decide how many times to jump.
  1240.    
  1241.    If you call this function, you must zero out pending_exact.  */
  1242.  
  1243. static void
  1244. store_jump_n (char *from, char opcode, char *to, unsigned n)
  1245. {
  1246.   from[0] = opcode;
  1247.   STORE_NUMBER (from + 1, to - (from + 3));
  1248.   STORE_NUMBER (from + 3, n);
  1249. }
  1250.  
  1251.  
  1252. /* Similar to insert_jump, but handles a jump which needs an extra
  1253.    number to handle minimum and maximum cases.  Open up space at
  1254.    location FROM, and insert there a jump to TO.  CURRENT_END gives the
  1255.    end of the storage in use, so we know how much data to copy up. OP is
  1256.    the opcode of the jump to insert.
  1257.  
  1258.    If you call this function, you must zero out pending_exact.  */
  1259.  
  1260. static void
  1261. insert_jump_n (char op, char *from, char *to, char *current_end, unsigned n)
  1262. {
  1263.   register char *pfrom = current_end;        /* Copy from here...  */
  1264.   register char *pto = current_end + 5;        /* ...to here.  */
  1265.  
  1266.   while (pfrom != from)                   
  1267.     *--pto = *--pfrom;
  1268.   store_jump_n (from, op, to, n);
  1269. }
  1270.  
  1271.  
  1272. /* Open up space at location THERE, and insert operation OP followed by
  1273.    NUM_1 and NUM_2.  CURRENT_END gives the end of the storage in use, so
  1274.    we know how much data to copy up.
  1275.  
  1276.    If you call this function, you must zero out pending_exact.  */
  1277.  
  1278. static void
  1279. insert_op_2 (char op, char *there, char *current_end, int num_1, int num_2)
  1280. {
  1281.   register char *pfrom = current_end;        /* Copy from here...  */
  1282.   register char *pto = current_end + 5;        /* ...to here.  */
  1283.  
  1284.   while (pfrom != there)                   
  1285.     *--pto = *--pfrom;
  1286.   
  1287.   there[0] = op;
  1288.   STORE_NUMBER (there + 1, num_1);
  1289.   STORE_NUMBER (there + 3, num_2);
  1290. }
  1291.  
  1292.  
  1293.  
  1294. /* Given a pattern, compute a fastmap from it.  The fastmap records
  1295.    which of the (1 << BYTEWIDTH) possible characters can start a string
  1296.    that matches the pattern.  This fastmap is used by re_search to skip
  1297.    quickly over totally implausible text.
  1298.  
  1299.    The caller must supply the address of a (1 << BYTEWIDTH)-byte data 
  1300.    area as bufp->fastmap.
  1301.    The other components of bufp describe the pattern to be used.  */
  1302.  
  1303. void
  1304. re_compile_fastmap (struct re_pattern_buffer *bufp)
  1305. {
  1306.   unsigned char *pattern = (unsigned char *) bufp->buffer;
  1307.   int size = bufp->used;
  1308.   register char *fastmap = bufp->fastmap;
  1309.   register unsigned char *p = pattern;
  1310.   register unsigned char *pend = pattern + size;
  1311.   register int j, k;
  1312.   unsigned char *translate = (unsigned char *) bufp->translate;
  1313.  
  1314.   unsigned char *stackb[NFAILURES];
  1315.   unsigned char **stackp = stackb;
  1316.  
  1317.   unsigned is_a_succeed_n;
  1318.  
  1319.   bzero (fastmap, (1 << BYTEWIDTH));
  1320.   bufp->fastmap_accurate = 1;
  1321.   bufp->can_be_null = 0;
  1322.       
  1323.   while (p)
  1324.     {
  1325.       is_a_succeed_n = 0;
  1326.       if (p == pend)
  1327.     {
  1328.       bufp->can_be_null = 1;
  1329.       break;
  1330.     }
  1331. #ifdef SWITCH_ENUM_BUG
  1332.       switch ((int) ((enum regexpcode) *p++))
  1333. #else
  1334.       switch ((enum regexpcode) *p++)
  1335. #endif
  1336.     {
  1337.     case exactn:
  1338.       if (translate)
  1339.         fastmap[translate[p[1]]] = 1;
  1340.       else
  1341.         fastmap[p[1]] = 1;
  1342.       break;
  1343.  
  1344.         case unused:
  1345.         case begline:
  1346. #ifdef emacs
  1347.         case before_dot:
  1348.     case at_dot:
  1349.     case after_dot:
  1350. #endif
  1351.     case begbuf:
  1352.     case endbuf:
  1353.     case wordbound:
  1354.     case notwordbound:
  1355.     case wordbeg:
  1356.     case wordend:
  1357.           continue;
  1358.  
  1359.     case endline:
  1360.       if (translate)
  1361.         fastmap[translate['\n']] = 1;
  1362.       else
  1363.         fastmap['\n'] = 1;
  1364.             
  1365.       if (bufp->can_be_null != 1)
  1366.         bufp->can_be_null = 2;
  1367.       break;
  1368.  
  1369.     case jump_n:
  1370.         case finalize_jump:
  1371.     case maybe_finalize_jump:
  1372.     case jump:
  1373.     case dummy_failure_jump:
  1374.           EXTRACT_NUMBER_AND_INCR (j, p);
  1375.       p += j;    
  1376.       if (j > 0)
  1377.         continue;
  1378.           /* Jump backward reached implies we just went through
  1379.          the body of a loop and matched nothing.
  1380.          Opcode jumped to should be an on_failure_jump.
  1381.          Just treat it like an ordinary jump.
  1382.          For a * loop, it has pushed its failure point already;
  1383.          If so, discard that as redundant.  */
  1384.  
  1385.           if ((enum regexpcode) *p != on_failure_jump
  1386.           && (enum regexpcode) *p != succeed_n)
  1387.         continue;
  1388.           p++;
  1389.           EXTRACT_NUMBER_AND_INCR (j, p);
  1390.           p += j;        
  1391.           if (stackp != stackb && *stackp == p)
  1392.             stackp--;
  1393.           continue;
  1394.       
  1395.         case on_failure_jump:
  1396.     handle_on_failure_jump:
  1397.           EXTRACT_NUMBER_AND_INCR (j, p);
  1398.           *++stackp = p + j;
  1399.       if (is_a_succeed_n)
  1400.             EXTRACT_NUMBER_AND_INCR (k, p);    /* Skip the n.  */
  1401.       continue;
  1402.  
  1403.     case succeed_n:
  1404.       is_a_succeed_n = 1;
  1405.           /* Get to the number of times to succeed.  */
  1406.           p += 2;        
  1407.       /* Increment p past the n for when k != 0.  */
  1408.           EXTRACT_NUMBER_AND_INCR (k, p);
  1409.           if (k == 0)
  1410.         {
  1411.               p -= 4;
  1412.               goto handle_on_failure_jump;
  1413.             }
  1414.           continue;
  1415.           
  1416.     case set_number_at:
  1417.           p += 4;
  1418.           continue;
  1419.  
  1420.         case start_memory:
  1421.     case stop_memory:
  1422.       p++;
  1423.       continue;
  1424.  
  1425.     case duplicate:
  1426.       bufp->can_be_null = 1;
  1427.       fastmap['\n'] = 1;
  1428.     case anychar:
  1429.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  1430.         if (j != '\n')
  1431.           fastmap[j] = 1;
  1432.       if (bufp->can_be_null)
  1433.         return;
  1434.       /* Don't return; check the alternative paths
  1435.          so we can set can_be_null if appropriate.  */
  1436.       break;
  1437.  
  1438.     case wordchar:
  1439.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  1440.         if (SYNTAX (j) == Sword)
  1441.           fastmap[j] = 1;
  1442.       break;
  1443.  
  1444.     case notwordchar:
  1445.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  1446.         if (SYNTAX (j) != Sword)
  1447.           fastmap[j] = 1;
  1448.       break;
  1449.  
  1450. #ifdef emacs
  1451.     case syntaxspec:
  1452.       k = *p++;
  1453.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  1454.         if (SYNTAX (j) == (enum syntaxcode) k)
  1455.           fastmap[j] = 1;
  1456.       break;
  1457.  
  1458.     case notsyntaxspec:
  1459.       k = *p++;
  1460.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  1461.         if (SYNTAX (j) != (enum syntaxcode) k)
  1462.           fastmap[j] = 1;
  1463.       break;
  1464. #endif /* not emacs */
  1465.  
  1466.     case charset:
  1467.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  1468.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  1469.           {
  1470.         if (translate)
  1471.           fastmap[translate[j]] = 1;
  1472.         else
  1473.           fastmap[j] = 1;
  1474.           }
  1475.       break;
  1476.  
  1477.     case charset_not:
  1478.       /* Chars beyond end of map must be allowed */
  1479.       for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  1480.         if (translate)
  1481.           fastmap[translate[j]] = 1;
  1482.         else
  1483.           fastmap[j] = 1;
  1484.  
  1485.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  1486.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  1487.           {
  1488.         if (translate)
  1489.           fastmap[translate[j]] = 1;
  1490.         else
  1491.           fastmap[j] = 1;
  1492.           }
  1493.       break;
  1494.     }
  1495.  
  1496.       /* Get here means we have successfully found the possible starting
  1497.          characters of one path of the pattern.  We need not follow this
  1498.          path any farther.  Instead, look at the next alternative
  1499.          remembered in the stack.  */
  1500.    if (stackp != stackb)
  1501.     p = *stackp--;
  1502.       else
  1503.     break;
  1504.     }
  1505. }
  1506.  
  1507.  
  1508.  
  1509. /* Like re_search_2, below, but only one string is specified, and
  1510.    doesn't let you say where to stop matching. */
  1511.  
  1512. int
  1513. re_search (struct re_pattern_buffer *pbufp,
  1514.        char *string,
  1515.        int size,
  1516.        int startpos,
  1517.        int range,
  1518.        struct re_registers *regs)
  1519. {
  1520.   return re_search_2 (pbufp, (char *) 0, 0, string, size, startpos, range, 
  1521.               regs, size);
  1522. }
  1523.  
  1524.  
  1525. /* Using the compiled pattern in PBUFP->buffer, first tries to match the
  1526.    virtual concatenation of STRING1 and STRING2, starting first at index
  1527.    STARTPOS, then at STARTPOS + 1, and so on.  RANGE is the number of
  1528.    places to try before giving up.  If RANGE is negative, it searches
  1529.    backwards, i.e., the starting positions tried are STARTPOS, STARTPOS
  1530.    - 1, etc.  STRING1 and STRING2 are of SIZE1 and SIZE2, respectively.
  1531.    In REGS, return the indices of the virtual concatenation of STRING1
  1532.    and STRING2 that matched the entire PBUFP->buffer and its contained
  1533.    subexpressions.  Do not consider matching one past the index MSTOP in
  1534.    the virtual concatenation of STRING1 and STRING2.
  1535.  
  1536.    The value returned is the position in the strings at which the match
  1537.    was found, or -1 if no match was found, or -2 if error (such as
  1538.    failure stack overflow).  */
  1539.  
  1540. int
  1541. re_search_2 (struct re_pattern_buffer *pbufp,
  1542.          char *string1, int size1,
  1543.          char *string2, int size2,
  1544.          int startpos,
  1545.          register int range,
  1546.          struct re_registers *regs,
  1547.          int mstop)
  1548. {
  1549.   register char *fastmap = pbufp->fastmap;
  1550.   register unsigned char *translate = (unsigned char *) pbufp->translate;
  1551.   int total_size = size1 + size2;
  1552.   int endpos = startpos + range;
  1553.   int val;
  1554.  
  1555.   /* Check for out-of-range starting position.  */
  1556.   if (startpos < 0  ||  startpos > total_size)
  1557.     return -1;
  1558.     
  1559.   /* Fix up range if it would eventually take startpos outside of the
  1560.      virtual concatenation of string1 and string2.  */
  1561.   if (endpos < -1)
  1562.     range = -1 - startpos;
  1563.   else if (endpos > total_size)
  1564.     range = total_size - startpos;
  1565.  
  1566.   /* Update the fastmap now if not correct already.  */
  1567.   if (fastmap && !pbufp->fastmap_accurate)
  1568.     re_compile_fastmap (pbufp);
  1569.   
  1570.   /* If the search isn't to be a backwards one, don't waste time in a
  1571.      long search for a pattern that says it is anchored.  */
  1572.   if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf
  1573.       && range > 0)
  1574.     {
  1575.       if (startpos > 0)
  1576.     return -1;
  1577.       else
  1578.     range = 1;
  1579.     }
  1580.  
  1581.   while (1)
  1582.     { 
  1583.       /* If a fastmap is supplied, skip quickly over characters that
  1584.          cannot possibly be the start of a match.  Note, however, that
  1585.          if the pattern can possibly match the null string, we must
  1586.          test it at each starting point so that we take the first null
  1587.          string we get.  */
  1588.  
  1589.       if (fastmap && startpos < total_size && pbufp->can_be_null != 1)
  1590.     {
  1591.       if (range > 0)    /* Searching forwards.  */
  1592.         {
  1593.           register int lim = 0;
  1594.           register unsigned char *p;
  1595.           int irange = range;
  1596.           if (startpos < size1 && startpos + range >= size1)
  1597.         lim = range - (size1 - startpos);
  1598.  
  1599.           p = ((unsigned char *)
  1600.            &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  1601.  
  1602.               while (range > lim && !fastmap[translate 
  1603.                                              ? translate[*p++]
  1604.                                              : *p++])
  1605.             range--;
  1606.           startpos += irange - range;
  1607.         }
  1608.       else                /* Searching backwards.  */
  1609.         {
  1610.           register unsigned char c;
  1611.  
  1612.               if (string1 == 0 || startpos >= size1)
  1613.         c = string2[startpos - size1];
  1614.           else 
  1615.         c = string1[startpos];
  1616.  
  1617.               c &= 0xff;
  1618.           if (translate ? !fastmap[translate[c]] : !fastmap[c])
  1619.         goto advance;
  1620.         }
  1621.     }
  1622.  
  1623.       if (range >= 0 && startpos == total_size
  1624.       && fastmap && pbufp->can_be_null == 0)
  1625.     return -1;
  1626.  
  1627.       val = re_match_2 (pbufp, string1, size1, string2, size2, startpos,
  1628.             regs, mstop);
  1629.       if (val >= 0)
  1630.     return startpos;
  1631.       if (val == -2)
  1632.     return -2;
  1633.  
  1634. #ifdef C_ALLOCA
  1635.       alloca (0);
  1636. #endif /* C_ALLOCA */
  1637.  
  1638.     advance:
  1639.       if (!range) 
  1640.         break;
  1641.       else if (range > 0) 
  1642.         {
  1643.           range--; 
  1644.           startpos++;
  1645.         }
  1646.       else
  1647.         {
  1648.           range++; 
  1649.           startpos--;
  1650.         }
  1651.     }
  1652.   return -1;
  1653. }
  1654.  
  1655.  
  1656.  
  1657. #ifndef emacs   /* emacs never uses this.  */
  1658. int
  1659. re_match (struct re_pattern_buffer *pbufp,
  1660.       char *string,
  1661.       int size,
  1662.       int pos,
  1663.       struct re_registers *regs)
  1664. {
  1665.   return re_match_2 (pbufp, (char *) 0, 0, string, size, pos, regs, size); 
  1666. }
  1667. #endif /* not emacs */
  1668.  
  1669.  
  1670. /* The following are used for re_match_2, defined below:  */
  1671.  
  1672. /* Roughly the maximum number of failure points on the stack.  Would be
  1673.    exactly that if always pushed MAX_NUM_FAILURE_ITEMS each time we failed.  */
  1674.    
  1675. int re_max_failures = 2000;
  1676.  
  1677. /* Routine used by re_match_2.  */
  1678. static int bcmp_translate (char *, char *, int, unsigned char *);
  1679.  
  1680.  
  1681. /* Structure and accessing macros used in re_match_2:  */
  1682.  
  1683. struct register_info
  1684. {
  1685.   unsigned is_active : 1;
  1686.   unsigned matched_something : 1;
  1687. };
  1688.  
  1689. #define IS_ACTIVE(R)  ((R).is_active)
  1690. #define MATCHED_SOMETHING(R)  ((R).matched_something)
  1691.  
  1692.  
  1693. /* Macros used by re_match_2:  */
  1694.  
  1695.  
  1696. /* I.e., regstart, regend, and reg_info.  */
  1697.  
  1698. #define NUM_REG_ITEMS  3
  1699.  
  1700. /* We push at most this many things on the stack whenever we
  1701.    fail.  The `+ 2' refers to PATTERN_PLACE and STRING_PLACE, which are
  1702.    arguments to the PUSH_FAILURE_POINT macro.  */
  1703.  
  1704. #define MAX_NUM_FAILURE_ITEMS   (RE_NREGS * NUM_REG_ITEMS + 2)
  1705.  
  1706.  
  1707. /* We push this many things on the stack whenever we fail.  */
  1708.  
  1709. #define NUM_FAILURE_ITEMS  (last_used_reg * NUM_REG_ITEMS + 2)
  1710.  
  1711.  
  1712. /* This pushes most of the information about the current state we will want
  1713.    if we ever fail back to it.  */
  1714.  
  1715. #define PUSH_FAILURE_POINT(pattern_place, string_place)            \
  1716.   {                                    \
  1717.     short last_used_reg, this_reg;                    \
  1718.                                     \
  1719.     /* Find out how many registers are active or have been matched.    \
  1720.        (Aside from register zero, which is only set at the end.)  */    \
  1721.     for (last_used_reg = RE_NREGS - 1; last_used_reg > 0; last_used_reg--)\
  1722.       if (regstart[last_used_reg] != (unsigned char *) -1)        \
  1723.         break;                                \
  1724.                                     \
  1725.     if (stacke - stackp < NUM_FAILURE_ITEMS)                \
  1726.       {                                    \
  1727.     unsigned char **stackx;                        \
  1728.     int len = stacke - stackb;                \
  1729.     if (len > re_max_failures * MAX_NUM_FAILURE_ITEMS)        \
  1730.       return -2;                            \
  1731.                                     \
  1732.         /* Roughly double the size of the stack.  */            \
  1733.         stackx = (unsigned char **) alloca (2 * len            \
  1734.                                             * sizeof (unsigned char *));\
  1735.     /* Only copy what is in use.  */                \
  1736.         bcopy (stackb, stackx, len * sizeof (char *));            \
  1737.     stackp = stackx + (stackp - stackb);                \
  1738.     stackb = stackx;                        \
  1739.     stacke = stackb + 2 * len;                    \
  1740.       }                                    \
  1741.                                     \
  1742.     /* Now push the info for each of those registers.  */        \
  1743.     for (this_reg = 1; this_reg <= last_used_reg; this_reg++)        \
  1744.       {                                    \
  1745.         *stackp++ = regstart[this_reg];                    \
  1746.         *stackp++ = regend[this_reg];                    \
  1747.         *stackp++ = (unsigned char *) ®_info[this_reg];        \
  1748.       }                                    \
  1749.                                     \
  1750.     /* Push how many registers we saved.  */                \
  1751.     *stackp++ = (unsigned char *) last_used_reg;            \
  1752.                                     \
  1753.     *stackp++ = pattern_place;                                          \
  1754.     *stackp++ = string_place;                                           \
  1755.   }
  1756.   
  1757.  
  1758. /* This pops what PUSH_FAILURE_POINT pushes.  */
  1759.  
  1760. #define POP_FAILURE_POINT()                        \
  1761.   {                                    \
  1762.     int temp;                                \
  1763.     stackp -= 2;        /* Remove failure points.  */        \
  1764.     temp = (int) *--stackp;    /* How many regs pushed.  */            \
  1765.     temp *= NUM_REG_ITEMS;    /* How much to take off the stack.  */    \
  1766.     stackp -= temp;         /* Remove the register info.  */    \
  1767.   }
  1768.  
  1769.  
  1770. #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
  1771.  
  1772. /* Is true if there is a first string and if PTR is pointing anywhere
  1773.    inside it or just past the end.  */
  1774.    
  1775. #define IS_IN_FIRST_STRING(ptr)                     \
  1776.     (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  1777.  
  1778. /* Call before fetching a character with *d.  This switches over to
  1779.    string2 if necessary.  */
  1780.  
  1781. #define PREFETCH                            \
  1782.  while (d == dend)                                \
  1783.   {                                    \
  1784.     /* end of string2 => fail.  */                    \
  1785.     if (dend == end_match_2)                         \
  1786.       goto fail;                            \
  1787.     /* end of string1 => advance to string2.  */             \
  1788.     d = string2;                                \
  1789.     dend = end_match_2;                            \
  1790.   }
  1791.  
  1792.  
  1793. /* Call this when have matched something; it sets `matched' flags for the
  1794.    registers corresponding to the subexpressions of which we currently
  1795.    are inside.  */
  1796. #define SET_REGS_MATCHED                         \
  1797.   { unsigned this_reg;                             \
  1798.     for (this_reg = 0; this_reg < RE_NREGS; this_reg++)         \
  1799.       {                                 \
  1800.         if (IS_ACTIVE(reg_info[this_reg]))                \
  1801.           MATCHED_SOMETHING(reg_info[this_reg]) = 1;            \
  1802.         else                                \
  1803.           MATCHED_SOMETHING(reg_info[this_reg]) = 0;            \
  1804.       }                                 \
  1805.   }
  1806.  
  1807. /* Test if at very beginning or at very end of the virtual concatenation
  1808.    of string1 and string2.  If there is only one string, we've put it in
  1809.    string2.  */
  1810.  
  1811. #define AT_STRINGS_BEG  (d == (size1 ? string1 : string2)  ||  !size2)
  1812. #define AT_STRINGS_END  (d == end2)    
  1813.  
  1814. #define AT_WORD_BOUNDARY                        \
  1815.   (AT_STRINGS_BEG || AT_STRINGS_END || IS_A_LETTER (d - 1) != IS_A_LETTER (d))
  1816.  
  1817. /* We have two special cases to check for: 
  1818.      1) if we're past the end of string1, we have to look at the first
  1819.         character in string2;
  1820.      2) if we're before the beginning of string2, we have to look at the
  1821.         last character in string1; we assume there is a string1, so use
  1822.         this in conjunction with AT_STRINGS_BEG.  */
  1823. #define IS_A_LETTER(d)                            \
  1824.   (SYNTAX ((d) == end1 ? *string2 : (d) == string2 - 1 ? *(end1 - 1) : *(d))\
  1825.    == Sword)
  1826.  
  1827.  
  1828. /* Match the pattern described by PBUFP against the virtual
  1829.    concatenation of STRING1 and STRING2, which are of SIZE1 and SIZE2,
  1830.    respectively.  Start the match at index POS in the virtual
  1831.    concatenation of STRING1 and STRING2.  In REGS, return the indices of
  1832.    the virtual concatenation of STRING1 and STRING2 that matched the
  1833.    entire PBUFP->buffer and its contained subexpressions.  Do not
  1834.    consider matching one past the index MSTOP in the virtual
  1835.    concatenation of STRING1 and STRING2.
  1836.  
  1837.    If pbufp->fastmap is nonzero, then it had better be up to date.
  1838.  
  1839.    The reason that the data to match are specified as two components
  1840.    which are to be regarded as concatenated is so this function can be
  1841.    used directly on the contents of an Emacs buffer.
  1842.  
  1843.    -1 is returned if there is no match.  -2 is returned if there is an
  1844.    error (such as match stack overflow).  Otherwise the value is the
  1845.    length of the substring which was matched.  */
  1846.  
  1847. int
  1848. re_match_2 (struct re_pattern_buffer *pbufp,
  1849.         char *string1_arg, int size1,
  1850.         char *string2_arg, int size2,
  1851.         int pos,
  1852.         struct re_registers *regs,
  1853.         int mstop)
  1854. {
  1855.   register unsigned char *p = (unsigned char *) pbufp->buffer;
  1856.  
  1857.   /* Pointer to beyond end of buffer.  */
  1858.   register unsigned char *pend = p + pbufp->used;
  1859.  
  1860.   unsigned char *string1 = (unsigned char *) string1_arg;
  1861.   unsigned char *string2 = (unsigned char *) string2_arg;
  1862.   unsigned char *end1;        /* Just past end of first string.  */
  1863.   unsigned char *end2;        /* Just past end of second string.  */
  1864.  
  1865.   /* Pointers into string1 and string2, just past the last characters in
  1866.      each to consider matching.  */
  1867.   unsigned char *end_match_1, *end_match_2;
  1868.  
  1869.   register unsigned char *d, *dend;
  1870.   register int mcnt;            /* Multipurpose.  */
  1871.   unsigned char *translate = (unsigned char *) pbufp->translate;
  1872.   unsigned is_a_jump_n = 0;
  1873.  
  1874.  /* Failure point stack.  Each place that can handle a failure further
  1875.     down the line pushes a failure point on this stack.  It consists of
  1876.     restart, regend, and reg_info for all registers corresponding to the
  1877.     subexpressions we're currently inside, plus the number of such
  1878.     registers, and, finally, two char *'s.  The first char * is where to
  1879.     resume scanning the pattern; the second one is where to resume
  1880.     scanning the strings.  If the latter is zero, the failure point is a
  1881.     ``dummy''; if a failure happens and the failure point is a dummy, it
  1882.     gets discarded and the next next one is tried.  */
  1883.  
  1884.   unsigned char *initial_stack[MAX_NUM_FAILURE_ITEMS * NFAILURES];
  1885.   unsigned char **stackb = initial_stack;
  1886.   unsigned char **stackp = stackb;
  1887.   unsigned char **stacke = &stackb[MAX_NUM_FAILURE_ITEMS * NFAILURES];
  1888.  
  1889.  
  1890.   /* Information on the contents of registers. These are pointers into
  1891.      the input strings; they record just what was matched (on this
  1892.      attempt) by a subexpression part of the pattern, that is, the
  1893.      regnum-th regstart pointer points to where in the pattern we began
  1894.      matching and the regnum-th regend points to right after where we
  1895.      stopped matching the regnum-th subexpression.  (The zeroth register
  1896.      keeps track of what the whole pattern matches.)  */
  1897.      
  1898.   unsigned char *regstart[RE_NREGS];
  1899.   unsigned char *regend[RE_NREGS];
  1900.  
  1901.   /* The is_active field of reg_info helps us keep track of which (possibly
  1902.      nested) subexpressions we are currently in. The matched_something
  1903.      field of reg_info[reg_num] helps us tell whether or not we have
  1904.      matched any of the pattern so far this time through the reg_num-th
  1905.      subexpression.  These two fields get reset each time through any
  1906.      loop their register is in.  */
  1907.  
  1908.   struct register_info reg_info[RE_NREGS];
  1909.  
  1910.  
  1911.   /* The following record the register info as found in the above
  1912.      variables when we find a match better than any we've seen before. 
  1913.      This happens as we backtrack through the failure points, which in
  1914.      turn happens only if we have not yet matched the entire string.  */
  1915.  
  1916.   unsigned best_regs_set = 0;
  1917.   unsigned char *best_regstart[RE_NREGS];
  1918.   unsigned char *best_regend[RE_NREGS];
  1919.  
  1920.   /* Initialize subexpression text positions to -1 to mark ones that no
  1921.      \( or ( and \) or ) has been seen for. Also set all registers to
  1922.      inactive and mark them as not having matched anything or ever
  1923.      failed.  */
  1924.   for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  1925.     {
  1926.       regstart[mcnt] = regend[mcnt] = (unsigned char *) -1;
  1927.       IS_ACTIVE (reg_info[mcnt]) = 0;
  1928.       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  1929.     }
  1930.   
  1931.   if (regs)
  1932.     for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  1933.       regs->start[mcnt] = regs->end[mcnt] = -1;
  1934.  
  1935.   /* Set up pointers to ends of strings.
  1936.      Don't allow the second string to be empty unless both are empty.  */
  1937.   if (size2 == 0)
  1938.     {
  1939.       string2 = string1;
  1940.       size2 = size1;
  1941.       string1 = 0;
  1942.       size1 = 0;
  1943.     }
  1944.   end1 = string1 + size1;
  1945.   end2 = string2 + size2;
  1946.  
  1947.   /* Compute where to stop matching, within the two strings.  */
  1948.   if (mstop <= size1)
  1949.     {
  1950.       end_match_1 = string1 + mstop;
  1951.       end_match_2 = string2;
  1952.     }
  1953.   else
  1954.     {
  1955.       end_match_1 = end1;
  1956.       end_match_2 = string2 + mstop - size1;
  1957.     }
  1958.  
  1959.   /* `p' scans through the pattern as `d' scans through the data. `dend'
  1960.      is the end of the input string that `d' points within. `d' is
  1961.      advanced into the following input string whenever necessary, but
  1962.      this happens before fetching; therefore, at the beginning of the
  1963.      loop, `d' can be pointing at the end of a string, but it cannot
  1964.      equal string2.  */
  1965.  
  1966.   if (size1 != 0 && pos <= size1)
  1967.     d = string1 + pos, dend = end_match_1;
  1968.   else
  1969.     d = string2 + pos - size1, dend = end_match_2;
  1970.  
  1971.  
  1972.   /* This loops over pattern commands.  It exits by returning from the
  1973.      function if match is complete, or it drops through if match fails
  1974.      at this starting point in the input data.  */
  1975.  
  1976.   while (1)
  1977.     {
  1978.       is_a_jump_n = 0;
  1979.       /* End of pattern means we might have succeeded.  */
  1980.       if (p == pend)
  1981.     {
  1982.       /* If not end of string, try backtracking.  Otherwise done.  */
  1983.           if (d != end_match_2)
  1984.         {
  1985.               if (stackp != stackb)
  1986.                 {
  1987.                   /* More failure points to try.  */
  1988.  
  1989.                   unsigned in_same_string = 
  1990.                           IS_IN_FIRST_STRING (best_regend[0]) 
  1991.                         == MATCHING_IN_FIRST_STRING;
  1992.  
  1993.                   /* If exceeds best match so far, save it.  */
  1994.                   if (! best_regs_set
  1995.                       || (in_same_string && d > best_regend[0])
  1996.                       || (! in_same_string && ! MATCHING_IN_FIRST_STRING))
  1997.                     {
  1998.                       best_regs_set = 1;
  1999.                       best_regend[0] = d;    /* Never use regstart[0].  */
  2000.                       
  2001.                       for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  2002.                         {
  2003.                           best_regstart[mcnt] = regstart[mcnt];
  2004.                           best_regend[mcnt] = regend[mcnt];
  2005.                         }
  2006.                     }
  2007.                   goto fail;           
  2008.                 }
  2009.               /* If no failure points, don't restore garbage.  */
  2010.               else if (best_regs_set)   
  2011.                 {
  2012.           restore_best_regs:
  2013.                   /* Restore best match.  */
  2014.                   d = best_regend[0];
  2015.                   
  2016.           for (mcnt = 0; mcnt < RE_NREGS; mcnt++)
  2017.             {
  2018.               regstart[mcnt] = best_regstart[mcnt];
  2019.               regend[mcnt] = best_regend[mcnt];
  2020.             }
  2021.                 }
  2022.             }
  2023.  
  2024.       /* If caller wants register contents data back, convert it 
  2025.          to indices.  */
  2026.       if (regs)
  2027.         {
  2028.           regs->start[0] = pos;
  2029.           if (MATCHING_IN_FIRST_STRING)
  2030.         regs->end[0] = d - string1;
  2031.           else
  2032.         regs->end[0] = d - string2 + size1;
  2033.           for (mcnt = 1; mcnt < RE_NREGS; mcnt++)
  2034.         {
  2035.           if (regend[mcnt] == (unsigned char *) -1)
  2036.             {
  2037.               regs->start[mcnt] = -1;
  2038.               regs->end[mcnt] = -1;
  2039.               continue;
  2040.             }
  2041.           if (IS_IN_FIRST_STRING (regstart[mcnt]))
  2042.             regs->start[mcnt] = regstart[mcnt] - string1;
  2043.           else
  2044.             regs->start[mcnt] = regstart[mcnt] - string2 + size1;
  2045.                     
  2046.           if (IS_IN_FIRST_STRING (regend[mcnt]))
  2047.             regs->end[mcnt] = regend[mcnt] - string1;
  2048.           else
  2049.             regs->end[mcnt] = regend[mcnt] - string2 + size1;
  2050.         }
  2051.         }
  2052.       return d - pos - (MATCHING_IN_FIRST_STRING 
  2053.                 ? string1 
  2054.                 : string2 - size1);
  2055.         }
  2056.  
  2057.       /* Otherwise match next pattern command.  */
  2058. #ifdef SWITCH_ENUM_BUG
  2059.       switch ((int) ((enum regexpcode) *p++))
  2060. #else
  2061.       switch ((enum regexpcode) *p++)
  2062. #endif
  2063.     {
  2064.  
  2065.     /* \( [or `(', as appropriate] is represented by start_memory,
  2066.            \) by stop_memory.  Both of those commands are followed by
  2067.            a register number in the next byte.  The text matched
  2068.            within the \( and \) is recorded under that number.  */
  2069.     case start_memory:
  2070.           regstart[*p] = d;
  2071.           IS_ACTIVE (reg_info[*p]) = 1;
  2072.           MATCHED_SOMETHING (reg_info[*p]) = 0;
  2073.           p++;
  2074.           break;
  2075.  
  2076.     case stop_memory:
  2077.           regend[*p] = d;
  2078.           IS_ACTIVE (reg_info[*p]) = 0;
  2079.  
  2080.           /* If just failed to match something this time around with a sub-
  2081.          expression that's in a loop, try to force exit from the loop.  */
  2082.           if ((! MATCHED_SOMETHING (reg_info[*p])
  2083.            || (enum regexpcode) p[-3] == start_memory)
  2084.           && (p + 1) != pend)              
  2085.             {
  2086.           register unsigned char *p2 = p + 1;
  2087.               mcnt = 0;
  2088.               switch (*p2++)
  2089.                 {
  2090.                   case jump_n:
  2091.             is_a_jump_n = 1;
  2092.                   case finalize_jump:
  2093.           case maybe_finalize_jump:
  2094.           case jump:
  2095.           case dummy_failure_jump:
  2096.                     EXTRACT_NUMBER_AND_INCR (mcnt, p2);
  2097.             if (is_a_jump_n)
  2098.               p2 += 2;
  2099.                     break;
  2100.                 }
  2101.           p2 += mcnt;
  2102.         
  2103.               /* If the next operation is a jump backwards in the pattern
  2104.              to an on_failure_jump, exit from the loop by forcing a
  2105.                  failure after pushing on the stack the on_failure_jump's 
  2106.                  jump in the pattern, and d.  */
  2107.           if (mcnt < 0 && (enum regexpcode) *p2++ == on_failure_jump)
  2108.         {
  2109.                   EXTRACT_NUMBER_AND_INCR (mcnt, p2);
  2110.                   PUSH_FAILURE_POINT (p2 + mcnt, d);
  2111.                   goto fail;
  2112.                 }
  2113.             }
  2114.           p++;
  2115.           break;
  2116.  
  2117.     /* \<digit> has been turned into a `duplicate' command which is
  2118.            followed by the numeric value of <digit> as the register number.  */
  2119.         case duplicate:
  2120.       {
  2121.         int regno = *p++;   /* Get which register to match against */
  2122.         register unsigned char *d2, *dend2;
  2123.  
  2124.         /* Where in input to try to start matching.  */
  2125.             d2 = regstart[regno];
  2126.             
  2127.             /* Where to stop matching; if both the place to start and
  2128.                the place to stop matching are in the same string, then
  2129.                set to the place to stop, otherwise, for now have to use
  2130.                the end of the first string.  */
  2131.  
  2132.             dend2 = ((IS_IN_FIRST_STRING (regstart[regno]) 
  2133.               == IS_IN_FIRST_STRING (regend[regno]))
  2134.              ? regend[regno] : end_match_1);
  2135.         while (1)
  2136.           {
  2137.         /* If necessary, advance to next segment in register
  2138.                    contents.  */
  2139.         while (d2 == dend2)
  2140.           {
  2141.             if (dend2 == end_match_2) break;
  2142.             if (dend2 == regend[regno]) break;
  2143.             d2 = string2, dend2 = regend[regno];  /* end of string1 => advance to string2. */
  2144.           }
  2145.         /* At end of register contents => success */
  2146.         if (d2 == dend2) break;
  2147.  
  2148.         /* If necessary, advance to next segment in data.  */
  2149.         PREFETCH;
  2150.  
  2151.         /* How many characters left in this segment to match.  */
  2152.         mcnt = dend - d;
  2153.                 
  2154.         /* Want how many consecutive characters we can match in
  2155.                    one shot, so, if necessary, adjust the count.  */
  2156.                 if (mcnt > dend2 - d2)
  2157.           mcnt = dend2 - d2;
  2158.                   
  2159.         /* Compare that many; failure if mismatch, else move
  2160.                    past them.  */
  2161.         if (translate 
  2162.                     ? bcmp_translate ((char*)d, (char*)d2, mcnt, translate) 
  2163.                     : bcmp (d, d2, mcnt))
  2164.           goto fail;
  2165.         d += mcnt, d2 += mcnt;
  2166.           }
  2167.       }
  2168.       break;
  2169.  
  2170.     case anychar:
  2171.       PREFETCH;      /* Fetch a data character. */
  2172.       /* Match anything but a newline, maybe even a null.  */
  2173.       if ((translate ? translate[*d] : *d) == '\n'
  2174.               || ((obscure_syntax & RE_DOT_NOT_NULL) 
  2175.                   && (translate ? translate[*d] : *d) == '\000'))
  2176.         goto fail;
  2177.       SET_REGS_MATCHED;
  2178.           d++;
  2179.       break;
  2180.  
  2181.     case charset:
  2182.     case charset_not:
  2183.       {
  2184.         int not = 0;        /* Nonzero for charset_not.  */
  2185.         register int c;
  2186.         if (*(p - 1) == (unsigned char) charset_not)
  2187.           not = 1;
  2188.  
  2189.         PREFETCH;        /* Fetch a data character. */
  2190.  
  2191.         if (translate)
  2192.           c = translate[*d];
  2193.         else
  2194.           c = *d;
  2195.  
  2196.         if (c < *p * BYTEWIDTH
  2197.         && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  2198.           not = !not;
  2199.  
  2200.         p += 1 + *p;
  2201.  
  2202.         if (!not) goto fail;
  2203.         SET_REGS_MATCHED;
  2204.             d++;
  2205.         break;
  2206.       }
  2207.  
  2208.     case begline:
  2209.           if ((size1 != 0 && d == string1)
  2210.               || (size1 == 0 && size2 != 0 && d == string2)
  2211.               || (d && d[-1] == '\n')
  2212.               || (size1 == 0 && size2 == 0))
  2213.             break;
  2214.           else
  2215.             goto fail;
  2216.             
  2217.     case endline:
  2218.       if (d == end2
  2219.           || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n'))
  2220.         break;
  2221.       goto fail;
  2222.  
  2223.     /* `or' constructs are handled by starting each alternative with
  2224.            an on_failure_jump that points to the start of the next
  2225.            alternative.  Each alternative except the last ends with a
  2226.            jump to the joining point.  (Actually, each jump except for
  2227.            the last one really jumps to the following jump, because
  2228.            tensioning the jumps is a hassle.)  */
  2229.  
  2230.     /* The start of a stupid repeat has an on_failure_jump that points
  2231.        past the end of the repeat text. This makes a failure point so 
  2232.            that on failure to match a repetition, matching restarts past
  2233.            as many repetitions have been found with no way to fail and
  2234.            look for another one.  */
  2235.  
  2236.     /* A smart repeat is similar but loops back to the on_failure_jump
  2237.        so that each repetition makes another failure point.  */
  2238.  
  2239.     case on_failure_jump:
  2240.         on_failure:
  2241.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2242.           PUSH_FAILURE_POINT (p + mcnt, d);
  2243.           break;
  2244.  
  2245.     /* The end of a smart repeat has a maybe_finalize_jump back.
  2246.        Change it either to a finalize_jump or an ordinary jump.  */
  2247.     case maybe_finalize_jump:
  2248.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2249.       {
  2250.         register unsigned char *p2 = p;
  2251.         /* Compare what follows with the beginning of the repeat.
  2252.            If we can establish that there is nothing that they would
  2253.            both match, we can change to finalize_jump.  */
  2254.         while (p2 + 1 != pend
  2255.            && (*p2 == (unsigned char) stop_memory
  2256.                || *p2 == (unsigned char) start_memory))
  2257.           p2 += 2;                /* Skip over reg number.  */
  2258.         if (p2 == pend)
  2259.           p[-3] = (unsigned char) finalize_jump;
  2260.         else if (*p2 == (unsigned char) exactn
  2261.              || *p2 == (unsigned char) endline)
  2262.           {
  2263.         register int c = *p2 == (unsigned char) endline ? '\n' : p2[2];
  2264.         register unsigned char *p1 = p + mcnt;
  2265.         /* p1[0] ... p1[2] are an on_failure_jump.
  2266.            Examine what follows that.  */
  2267.         if (p1[3] == (unsigned char) exactn && p1[5] != c)
  2268.           p[-3] = (unsigned char) finalize_jump;
  2269.         else if (p1[3] == (unsigned char) charset
  2270.              || p1[3] == (unsigned char) charset_not)
  2271.           {
  2272.             int not = p1[3] == (unsigned char) charset_not;
  2273.             if (c < p1[4] * BYTEWIDTH
  2274.             && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  2275.               not = !not;
  2276.             /* `not' is 1 if c would match.  */
  2277.             /* That means it is not safe to finalize.  */
  2278.             if (!not)
  2279.               p[-3] = (unsigned char) finalize_jump;
  2280.           }
  2281.           }
  2282.       }
  2283.       p -= 2;        /* Point at relative address again.  */
  2284.       if (p[-1] != (unsigned char) finalize_jump)
  2285.         {
  2286.           p[-1] = (unsigned char) jump;    
  2287.           goto nofinalize;
  2288.         }
  2289.         /* Note fall through.  */
  2290.  
  2291.     /* The end of a stupid repeat has a finalize_jump back to the
  2292.            start, where another failure point will be made which will
  2293.            point to after all the repetitions found so far.  */
  2294.  
  2295.         /* Take off failure points put on by matching on_failure_jump 
  2296.            because didn't fail.  Also remove the register information
  2297.            put on by the on_failure_jump.  */
  2298.         case finalize_jump:
  2299.           POP_FAILURE_POINT ();
  2300.         /* Note fall through.  */
  2301.         
  2302.     /* Jump without taking off any failure points.  */
  2303.         case jump:
  2304.     nofinalize:
  2305.       EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2306.       p += mcnt;
  2307.       break;
  2308.  
  2309.         case dummy_failure_jump:
  2310.           /* Normally, the on_failure_jump pushes a failure point, which
  2311.              then gets popped at finalize_jump.  We will end up at
  2312.              finalize_jump, also, and with a pattern of, say, `a+', we
  2313.              are skipping over the on_failure_jump, so we have to push
  2314.              something meaningless for finalize_jump to pop.  */
  2315.           PUSH_FAILURE_POINT (0, 0);
  2316.           goto nofinalize;
  2317.  
  2318.  
  2319.         /* Have to succeed matching what follows at least n times.  Then
  2320.           just handle like an on_failure_jump.  */
  2321.         case succeed_n: 
  2322.           EXTRACT_NUMBER (mcnt, p + 2);
  2323.           /* Originally, this is how many times we HAVE to succeed.  */
  2324.           if (mcnt)
  2325.             {
  2326.                mcnt--;
  2327.            p += 2;
  2328.                STORE_NUMBER_AND_INCR (p, mcnt);
  2329.             }
  2330.       else if (mcnt == 0)
  2331.             {
  2332.           p[2] = unused;
  2333.               p[3] = unused;
  2334.               goto on_failure;
  2335.             }
  2336.           else
  2337.         { 
  2338.               fprintf (stderr, "regex: the succeed_n's n is not set.\n");
  2339.               exit (1);
  2340.         }
  2341.           break;
  2342.         
  2343.         case jump_n: 
  2344.           EXTRACT_NUMBER (mcnt, p + 2);
  2345.           /* Originally, this is how many times we CAN jump.  */
  2346.           if (mcnt)
  2347.             {
  2348.                mcnt--;
  2349.                STORE_NUMBER(p + 2, mcnt);
  2350.            goto nofinalize;         /* Do the jump without taking off
  2351.                             any failure points.  */
  2352.             }
  2353.           /* If don't have to jump any more, skip over the rest of command.  */
  2354.       else      
  2355.         p += 4;             
  2356.           break;
  2357.         
  2358.     case set_number_at:
  2359.       {
  2360.           register unsigned char *p1;
  2361.  
  2362.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2363.             p1 = p + mcnt;
  2364.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  2365.         STORE_NUMBER (p1, mcnt);
  2366.             break;
  2367.           }
  2368.  
  2369.         /* Ignore these.  Used to ignore the n of succeed_n's which
  2370.            currently have n == 0.  */
  2371.         case unused:
  2372.           break;
  2373.  
  2374.         case wordbound:
  2375.       if (AT_WORD_BOUNDARY)
  2376.         break;
  2377.       goto fail;
  2378.  
  2379.     case notwordbound:
  2380.       if (AT_WORD_BOUNDARY)
  2381.         goto fail;
  2382.       break;
  2383.  
  2384.     case wordbeg:
  2385.           /* Have to check if AT_STRINGS_BEG before looking at d - 1.  */
  2386.       if (IS_A_LETTER (d) && (AT_STRINGS_BEG || !IS_A_LETTER (d - 1)))
  2387.         break;
  2388.       goto fail;
  2389.  
  2390.     case wordend:
  2391.           /* Have to check if AT_STRINGS_BEG before looking at d - 1.  */
  2392.       if (!AT_STRINGS_BEG && IS_A_LETTER (d - 1) 
  2393.               && (!IS_A_LETTER (d) || AT_STRINGS_END))
  2394.         break;
  2395.       goto fail;
  2396.  
  2397. #ifdef emacs
  2398.     case before_dot:
  2399.       if (PTR_CHAR_POS (d) >= point)
  2400.         goto fail;
  2401.       break;
  2402.  
  2403.     case at_dot:
  2404.       if (PTR_CHAR_POS (d) != point)
  2405.         goto fail;
  2406.       break;
  2407.  
  2408.     case after_dot:
  2409.       if (PTR_CHAR_POS (d) <= point)
  2410.         goto fail;
  2411.       break;
  2412.  
  2413.     case wordchar:
  2414.       mcnt = (int) Sword;
  2415.       goto matchsyntax;
  2416.  
  2417.     case syntaxspec:
  2418.       mcnt = *p++;
  2419.     matchsyntax:
  2420.       PREFETCH;
  2421.       if (SYNTAX (*d++) != (enum syntaxcode) mcnt) goto fail;
  2422.           SET_REGS_MATCHED;
  2423.       break;
  2424.       
  2425.     case notwordchar:
  2426.       mcnt = (int) Sword;
  2427.       goto matchnotsyntax;
  2428.  
  2429.     case notsyntaxspec:
  2430.       mcnt = *p++;
  2431.     matchnotsyntax:
  2432.       PREFETCH;
  2433.       if (SYNTAX (*d++) == (enum syntaxcode) mcnt) goto fail;
  2434.       SET_REGS_MATCHED;
  2435.           break;
  2436.  
  2437. #else /* not emacs */
  2438.  
  2439.     case wordchar:
  2440.       PREFETCH;
  2441.           if (!IS_A_LETTER (d))
  2442.             goto fail;
  2443.       SET_REGS_MATCHED;
  2444.       break;
  2445.       
  2446.     case notwordchar:
  2447.       PREFETCH;
  2448.       if (IS_A_LETTER (d))
  2449.             goto fail;
  2450.           SET_REGS_MATCHED;
  2451.       break;
  2452.  
  2453. #endif /* not emacs */
  2454.  
  2455.     case begbuf:
  2456.           if (AT_STRINGS_BEG)
  2457.             break;
  2458.           goto fail;
  2459.  
  2460.         case endbuf:
  2461.       if (AT_STRINGS_END)
  2462.         break;
  2463.       goto fail;
  2464.  
  2465.     case exactn:
  2466.       /* Match the next few pattern characters exactly.
  2467.          mcnt is how many characters to match.  */
  2468.       mcnt = *p++;
  2469.       /* This is written out as an if-else so we don't waste time
  2470.              testing `translate' inside the loop.  */
  2471.           if (translate)
  2472.         {
  2473.           do
  2474.         {
  2475.           PREFETCH;
  2476.           if (translate[*d++] != *p++) goto fail;
  2477.         }
  2478.           while (--mcnt);
  2479.         }
  2480.       else
  2481.         {
  2482.           do
  2483.         {
  2484.           PREFETCH;
  2485.           if (*d++ != *p++) goto fail;
  2486.         }
  2487.           while (--mcnt);
  2488.         }
  2489.       SET_REGS_MATCHED;
  2490.           break;
  2491.     }
  2492.       continue;  /* Successfully executed one pattern command; keep going.  */
  2493.  
  2494.     /* Jump here if any matching operation fails. */
  2495.     fail:
  2496.       if (stackp != stackb)
  2497.     /* A restart point is known.  Restart there and pop it. */
  2498.     {
  2499.           short last_used_reg, this_reg;
  2500.           
  2501.           /* If this failure point is from a dummy_failure_point, just
  2502.              skip it.  */
  2503.       if (!stackp[-2])
  2504.             {
  2505.               POP_FAILURE_POINT ();
  2506.               goto fail;
  2507.             }
  2508.  
  2509.           d = *--stackp;
  2510.       p = *--stackp;
  2511.           if (d >= string1 && d <= end1)
  2512.         dend = end_match_1;
  2513.           /* Restore register info.  */
  2514.           last_used_reg = (short) *--stackp;
  2515.           
  2516.           /* Make the ones that weren't saved -1 or 0 again.  */
  2517.           for (this_reg = RE_NREGS - 1; this_reg > last_used_reg; this_reg--)
  2518.             {
  2519.               regend[this_reg] = (unsigned char *) -1;
  2520.               regstart[this_reg] = (unsigned char *) -1;
  2521.               IS_ACTIVE (reg_info[this_reg]) = 0;
  2522.               MATCHED_SOMETHING (reg_info[this_reg]) = 0;
  2523.             }
  2524.           
  2525.           /* And restore the rest from the stack.  */
  2526.           for ( ; this_reg > 0; this_reg--)
  2527.             {
  2528.               reg_info[this_reg] = *(struct register_info *) *--stackp;
  2529.               regend[this_reg] = *--stackp;
  2530.               regstart[this_reg] = *--stackp;
  2531.             }
  2532.     }
  2533.       else
  2534.         break;   /* Matching at this starting point really fails.  */
  2535.     }
  2536.  
  2537.   if (best_regs_set)
  2538.     goto restore_best_regs;
  2539.   return -1;                     /* Failure to match.  */
  2540. }
  2541.  
  2542.  
  2543. static int
  2544. bcmp_translate (char *s1, char *s2, int len, unsigned char *translate)
  2545. {
  2546.   register unsigned char *p1 = (unsigned char*)s1;
  2547.   register unsigned char *p2 = (unsigned char*)s2;
  2548.   while (len)
  2549.     {
  2550.       if (translate [*p1++] != translate [*p2++]) return 1;
  2551.       len--;
  2552.     }
  2553.   return 0;
  2554. }
  2555.  
  2556.  
  2557.  
  2558. /* Entry points compatible with 4.2 BSD regex library.  */
  2559.  
  2560. #ifndef emacs
  2561.  
  2562. static struct re_pattern_buffer re_comp_buf;
  2563.  
  2564. char *
  2565. re_comp (char *s)
  2566. {
  2567.   if (!s)
  2568.     {
  2569.       if (!re_comp_buf.buffer)
  2570.     return "No previous regular expression";
  2571.       return 0;
  2572.     }
  2573.  
  2574.   if (!re_comp_buf.buffer)
  2575.     {
  2576.       if (!(re_comp_buf.buffer = (char *) malloc (200)))
  2577.     return "Memory exhausted";
  2578.       re_comp_buf.allocated = 200;
  2579.       if (!(re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH)))
  2580.     return "Memory exhausted";
  2581.     }
  2582.   return re_compile_pattern (s, strlen (s), &re_comp_buf);
  2583. }
  2584.  
  2585. int
  2586. re_exec (char *s)
  2587. {
  2588.   int len = strlen (s);
  2589.   return 0 <= re_search (&re_comp_buf, s, len, 0, len,
  2590.              (struct re_registers *) 0);
  2591. }
  2592. #endif /* not emacs */
  2593.  
  2594.  
  2595.  
  2596. #ifdef test
  2597.  
  2598. #include <stdio.h>
  2599.  
  2600. /* Indexed by a character, gives the upper case equivalent of the
  2601.    character.  */
  2602.  
  2603. char upcase[0400] = 
  2604.   { 000, 001, 002, 003, 004, 005, 006, 007,
  2605.     010, 011, 012, 013, 014, 015, 016, 017,
  2606.     020, 021, 022, 023, 024, 025, 026, 027,
  2607.     030, 031, 032, 033, 034, 035, 036, 037,
  2608.     040, 041, 042, 043, 044, 045, 046, 047,
  2609.     050, 051, 052, 053, 054, 055, 056, 057,
  2610.     060, 061, 062, 063, 064, 065, 066, 067,
  2611.     070, 071, 072, 073, 074, 075, 076, 077,
  2612.     0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  2613.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  2614.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  2615.     0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137,
  2616.     0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  2617.     0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  2618.     0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  2619.     0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177,
  2620.     0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  2621.     0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
  2622.     0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
  2623.     0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
  2624.     0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
  2625.     0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  2626.     0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  2627.     0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  2628.     0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  2629.     0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
  2630.     0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
  2631.     0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  2632.     0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  2633.     0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
  2634.     0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  2635.     0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  2636.   };
  2637.  
  2638. #ifdef canned
  2639.  
  2640. #include "tests.h"
  2641.  
  2642. typedef enum { extended_test, basic_test } test_type;
  2643.  
  2644. /* Use this to run the tests we've thought of.  */
  2645.  
  2646. void
  2647. main ()
  2648. {
  2649.   test_type t = extended_test;
  2650.  
  2651.   if (t == basic_test)
  2652.     {
  2653.       printf ("Running basic tests:\n\n");
  2654.       test_posix_basic ();
  2655.     }
  2656.   else if (t == extended_test)
  2657.     {
  2658.       printf ("Running extended tests:\n\n");
  2659.       test_posix_extended (); 
  2660.     }
  2661. }
  2662.  
  2663. #else /* not canned */
  2664.  
  2665. /* Use this to run interactive tests.  */
  2666.  
  2667. void
  2668. main (int argc, char **argv)
  2669. {
  2670.   char pat[80];
  2671.   struct re_pattern_buffer buf;
  2672.   int i;
  2673.   char c;
  2674.   char fastmap[(1 << BYTEWIDTH)];
  2675.  
  2676.   /* Allow a command argument to specify the style of syntax.  */
  2677.   if (argc > 1)
  2678.     obscure_syntax = atoi (argv[1]);
  2679.  
  2680.   buf.allocated = 40;
  2681.   buf.buffer = (char *) malloc (buf.allocated);
  2682.   buf.fastmap = fastmap;
  2683.   buf.translate = upcase;
  2684.  
  2685.   while (1)
  2686.     {
  2687.       gets (pat);
  2688.  
  2689.       if (*pat)
  2690.     {
  2691.           re_compile_pattern (pat, strlen(pat), &buf);
  2692.  
  2693.       for (i = 0; i < buf.used; i++)
  2694.         printchar (buf.buffer[i]);
  2695.  
  2696.       putchar ('\n');
  2697.  
  2698.       printf ("%d allocated, %d used.\n", buf.allocated, buf.used);
  2699.  
  2700.       re_compile_fastmap (&buf);
  2701.       printf ("Allowed by fastmap: ");
  2702.       for (i = 0; i < (1 << BYTEWIDTH); i++)
  2703.         if (fastmap[i]) printchar (i);
  2704.       putchar ('\n');
  2705.     }
  2706.  
  2707.       gets (pat);    /* Now read the string to match against */
  2708.  
  2709.       i = re_match (&buf, pat, strlen (pat), 0, 0);
  2710.       printf ("Match value %d.\n", i);
  2711.     }
  2712. }
  2713.  
  2714. #endif
  2715.  
  2716.  
  2717. #ifdef NOTDEF
  2718. void 
  2719. print_buf (struct re_pattern_buffer *bufpbufp)
  2720. {
  2721.   int i;
  2722.  
  2723.   printf ("buf is :\n----------------\n");
  2724.   for (i = 0; i < bufp->used; i++)
  2725.     printchar (bufp->buffer[i]);
  2726.   
  2727.   printf ("\n%d allocated, %d used.\n", bufp->allocated, bufp->used);
  2728.   
  2729.   printf ("Allowed by fastmap: ");
  2730.   for (i = 0; i < (1 << BYTEWIDTH); i++)
  2731.     if (bufp->fastmap[i])
  2732.       printchar (i);
  2733.   printf ("\nAllowed by translate: ");
  2734.   if (bufp->translate)
  2735.     for (i = 0; i < (1 << BYTEWIDTH); i++)
  2736.       if (bufp->translate[i])
  2737.     printchar (i);
  2738.   printf ("\nfastmap is%s accurate\n", bufp->fastmap_accurate ? "" : "n't");
  2739.   printf ("can %s be null\n----------", bufp->can_be_null ? "" : "not");
  2740. }
  2741. #endif /* NOTDEF */
  2742.  
  2743. void
  2744. printchar (char c)
  2745. {
  2746.   if (c < 040 || c >= 0177)
  2747.     {
  2748.       putchar ('\\');
  2749.       putchar (((c >> 6) & 3) + '0');
  2750.       putchar (((c >> 3) & 7) + '0');
  2751.       putchar ((c & 7) + '0');
  2752.     }
  2753.   else
  2754.     putchar (c);
  2755. }
  2756.  
  2757. void
  2758. error (char *string)
  2759. {
  2760.   puts (string);
  2761.   exit (1);
  2762. }
  2763. #endif /* test */
  2764.